#internals-and-peps
1 messages · Page 92 of 1
but I've never seen a lense used, so I'm unsure what problem you're solving there
if asked, I'd give the lens return an annotation of Tuple[Union[Tuple[int, ...], int]]
I was making an animation library that used immutable values, which proved to be very good for spreading the animation rendering across threads/processes
now that I think about it more, those tuples can be infinitely nested hm?
how would a strictly typed lang solve that same problem?
The issue is that first has the type Lens[Tuple[A, C], Tuple[B, C], A, B] (it changes an A to a B inside of Tuple[A, C]). And that annotation is illegal -- for no good reason IMO
It's possible in Haskell
(for example)
why doesn't that work?
@flat gazelle comin' in with the typing lib fix 😂
@flat gazelle you can read this thread https://github.com/microsoft/pyright/discussions/1380
The answer is basically: "No, this isn't allowed by PEP 484. "
I'm not sure why he's so worried about being compliant with PEPs, since typecheckers are already mutually incompatible
would Callable[[None], Lens[tuple[A, C], tuple[B, C], A, B]]] work
You could make a function
def f() -> Lens[Tuple[A, C], Tuple[B, C], A, B]:
...
but then type inference doesn't work out... for some reason
maybe it's somehow fixed in the new version, let me see in a minute
btw, if you do
def f(a: A) -> A:
return a
g: ? = f
you can't put anything in place of g that would preserve the type
nope, just checked
I guess no polymorphic values. Shame, but understandable.
hello, could you suggest which is the best tool for static code analysis for python (despite pylint which is already in place in our project) ?
mypy?
If you need a type checker, I would recommend pyright (which is included in Pylance if you're using VSCode)
I like mypy & flake8
thanks everyone. have tested mypy already and it is showing soo many errors in legacy code (where we didn't use types descriptions) omg..
I wonder if Python has a mechanism for interfaces. I want to do type hinting that behaves like Go's interface instead of having to do abstract classes.
typing.Protocol?
Hmm, let me check...
Oh nice!
I assume it works with "magic" methods (like __init__, __call__, etc)
Work in what sense?
Check that there's a __call__ method for instance
I know there's Callable, but just for example
Nice, thank you!
Speaking of Protocols
I actually like them better over subclassing unless I have good reason to do code sharing
Outside of the realm of type checking, you also have virtual subclasses either with the register or a subclass hook. That's how most ABC/protocols are able to allow for flexible isinstance checking anyway.
yeah
with @runtime_checkable
But most of the time isinstance isn't really needed
(unless you're writing some library)
Yes, it's more meant for situations in which you want your types to be able to checked against ABC protocols in a goose typing kind of way.
Is that for 3.10?
yes
There are some cool things in 3.10
Finally
I'm trying to remember a type-hinting PEP that basically allowed for extra metadata to be put on types
Or is that even a proper PEP? I'm not sure
I wonder what part of LL1 was needed that the old parser couldn’t do
Annotated?
!pep 593
Ah yeah
Was wondering if it's possible to write a mypy extension that does some rigid form of dependent types
Too much lookhead for the with I believe
Gotcha makes sense
*for the as, not for the with
You can make inline code blocks by wrapping text within backticks: `hello` -> hello
How much overhead does having __del__ add to cpython? I assume when it comes time to destroy an object it first checks to see if __del__ is defined rather than calling it with the possibility that it doesn't do anything. But that would still be a check that has to be performed for every PyObject.
I don't have any number, but I wouldn't expect much
Such behaviors are already used a bit everywhere in the language
Take __getattribute__ for example
It will be called very often, compared to __del__
I think if you put it in context, it is fairly negligeable
Yeah its one I completely dislike doing and why I am not a big fan of class wrappers
even __getattr__ slows stuff down big time.
Thought this was interesting, for anyone who doesn't follow Guido on Twitter:
What does this print?
x = 0
y = 0
def f():
x = 1
y = 1
class C:
print(x, y) # What does this print?
x = 2
f()
From https://t.co/8iZEYr23rx (@kevmod) Still in Python 3.9!
315
1421
Ah, the embed messes up the indentation, sorry 
Yeah it's weird. It was discussed here a few days ago.
Ah right. Missed that convo.
Had me wondering what a legitimate use case of a class definition within a function would be.
It's not something I recall seeing done in practice
Isn't that like the definition of a class factory
I don't think so. Don't those return instances rather than creating new types?
Technically a class is an instance of type but lets ignore that
doesnt namedtuple do something like that?
It's what a class decorator would do
depends on what the decorator does. if its just pulling information from the class definition then that makes sense, otherwise its easier to just modify the passed in class
I do have some code at work where there is a function that returns new subclasses. However I do it the sane way with types.new_class and it passes the args to __init_subclass__
manim has a somewhat unholy interface where you can only define a scene with a class, so if you want to dynamically generate a scene, you need something like this https://github.com/gurkult/py-gurklang/blob/master/gurklang/plugins/manim_visualization.py#L204
Maybe there's a way with subclassing Scene, but I doubt it's a better solution
Good point on the class decorator
...because its constructor is private AFAICT
Yeah unholy is a good way to describe that manim code
You gotta do what you gotta do
well, I tried to keep it as coherent as possible
bleh, TIL https://www.python.org/dev/peps/pep-0328/#relative-imports-and-name
is this what learning Python becomes after a while, reading PEPs?
That and looking forward to future releases
oh boi, moar reading 😴
Hey, i've been trying to use lz4 in python for quite a bit now
i have the package installed via pip
but when i try to run it, i get this
it's odd because the versions binary is in the folder
from .version import version as __version__
VERSION = __version__
from ._version import ( # noqa: F401
library_version_number,
library_version_string,
)
here is what's inside the init
all integers from -3 to 256 are in an internal array and only ever exist once
it saves memory. ints are full objects just like everything else, and consider how many ones there are in an average python program
yes
I think it's -5 to 256 inclusive actually (https://github.com/python/cpython/blob/master/Include/internal/pycore_interp.h#L217), but same idea
is there any big-o-analysis plugin for vscode?
There is no such tool that can be used to analyse big o of any algorithm
You have to do that manually
cool, yet it seems very feasible to construct such plugin
is there a way to get into open source programming with python? like - i have a decent understanding of python (and dart) and want to contribute, but have no idea what projects i could do some simple things in
can someone explain to me why co_nlocals is used in various places if you could also just check PyTuple_GET_SIZE(co_varnames)?
afaik its because its more optimized
ceval.c is one of the most heavily optimized parts of the interpreter
I guess that makes sense yeah
@errant apex dart/flutter front end and python backend, use python with database and make a pretty graph output in dart
Huh I never thought about using dart outside of flutter actually.
oh well, afaik (I've just touched flutter a bit), the big pro of flutter is that it's good for making pretty lightweight 2d omniplatform apps, so go make some more computation heavy thing like ML in python and display it in flutter?
Imho fiddling with tkinter is just a waste of time
i don't like tkinter
I'd use flask befrore tkinter
but I'm a professional mobile dev and work with flutter
how do you create a URL?
what do you mean create an url?
So I've been using kivy and want to move it over to my phone... does anyone know how?
Which data structure is the Python list?
an automatically growing and shrinking array
Dynamic array?
it is an array of pointers to python objects if that's what you are asking
ok thx 👍
Yeah, it's a dynamic array of pointers to objects.
is List similar to Rust's Vec? it basically has an internal buffer it manages and a length it keeps track of?
yes
though all of its elements are always pointers
whereas in rust you can get other types too
via traits yeah
No, like, you can have values (like numbers), not pointers in a vec in Rust
whereas in Python there's always another layer of indirection
oh, I thought they were making a point about hetero types
and that's not allowed
like a website
What do you call matrix , 2d array and other stuff
not sure what you mean. Those are words?

What do you call those
lists?
list with lists in it
well, it depends on what you call "type"
Hmm
does [1, 2, 3] have the same type as ["a", "b", "c"]?
Technically yes, but it's useful to think of the first one as list[int], and the second one as list[str].
And if you want to use type hints, those are "different types".
What i mean by those is like asking what a data structure is or something alike
you're asking what a list is?
A matrix is just a mathematical object
Matrix and what stuff
I don't think there's a common name for two-dimensional things
data structures?
Containers?
But theres no matrix thing in python
The closest you could get is to nest lists
Not even numpy uses a matrix class anymore
How about 2d arrays and stuff
usually a matrix is another name for 2d array
and, "and stuff" is a bit too vague to answer
@distant girder can you say what the "other things" have in common?
what characteristics are you looking for?
it is a data structure

https://paste.tortoisecommunity.com/egorekobot.py VS https://paste.tortoisecommunity.com/ayaxedugur.py
this may look like #python-general discussion but it is not i guess?
the question here is it better to call a train of function until it meets a certain condition or is it better to have a while true and call the function every time it is needed
IMO it is suited for #software-architecture
@distant girder you might need to be more specific about what you mean by "train of functions". Can you give examples that are brief enough that they fit in this chat?
There's a lot of overlap between what is appropriate for these two channels, honestly. If one frames the question as "which software design pattern is more Pythonic?", that would make it more specific to this channel.
😕
what i meant was is it better for your code to have a function calling a function then another function and so on until it meets a required argument or just make a function that calls those function one by one and those function called returns something
i guess 'which software design is more efficient and better?' i guess?
You should probably pick whichever design will make your code easiest for humans to deal with, unless you're writing something that is truly performance-critical.
Loops are more computationaly efficient than recursive function calls, if that's what it really comes down to.
Are dictionary keys unordered?
not any more
Not since python 3.7+, in which they retain insertion order
So the order depends on the insertion right?
Yep, (at least in the cpython implementation)
names = {}
names['id'] = True
names['owner'] = True
names['description'] = True
# Then later use it like this...
some_data[names.keys()[0]]
.keys() are not subscriptable tho
dict_keys objects aren't, but since theyre iterable you can cast it to a list and then index it
Well, in this case you could just use next(iter(names))
I still can't access the keys by index though
I want to use it to populate a table, so like
some_data[tuple(names.keys())[column_index]]
Maybe I should just keep a dictionary for fast checking and a list to retrieve the key
In all implementations, since 3.7. It was only a CPython implementation detail in 3.6
is there any other way to freeze time other than:
import time
time.sleep(#)
I ment for creating a game
no, i can show you, just wait a sec
thats a part of the code
Can you open a help channel? This channel isn't the right one for this
Most game I knew just waste CPU cycles to wait for the next frame render lol
Pardon me cause I cant recall, but I remember reading something about initiating an empty list as a bad practice due to some possible weird issues with that, can anybody tell if its true and what this is all about?
I have never heard of that
What should I do if I want to initialize resources (e.g. database connection, data, etc) for each process when using multiprocessing?
Do I just need to initialize them all before if __name__ == '__main__'?
Probably not, since you don’t want to store them as global afaik
Hello @unkempt rock, please see #❓|how-to-get-help
Hmm, what should I do then?
I was thinking of something like
from multiprocessing import Pool, freeze_support
import some_lib
process_resource = some_lib.get_some_resource()
def do_something(arg):
process_resource.do_stuff(arg)
if __name__ == '__main__':
freeze_support()
with Pool(16) as p:
p.map(do_something, [... some data])
some_lib is just a placeholder, forgot to put the from multiprocessing import Pool, freeze_support
You do know how sometimes you just write mockup codes that don't actually run but give a general idea of how they are expected to work, right?
Nope, I need some queues
Did that person get banned? Lol
2 of them actually
is this a more serious channel to ask questions in?
This is a channel for discussions about how the Python language itself functions
can you ask questions about that?
my questions not so much of an error as explaining a behavior I found
as long as it fits in the channel topic
I’ve read Kite’s description for SystemError
And apparently it’s like an internal error
Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).
You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception’s associated value) and if possible the source of the program that triggered the error.
Lol
Is there any builtin libraries that can be used to check if a file is being used/written?
You could just wrap around lsof on unix, idk for win
It seems that people are recommending using psutil for portability
I don't think it would work if the file is being used by root and the script checking for usage is not privileged
I guess you could go straight ahead and just try opening the file, catching a permission error
I'm trying to create a hot folder on Linux that will move files to other directory and process them there
Just give them chmod 777 if you can and should work
I don't think that would work, my last two tries corrupted some files and crashed the whole system because I was doing it through NFS
Maybe I need to use inotify
Thats totally not the 777s fault lol
The problem is not file permissions but race condition
Sounds complicated, can you explain a bit?
I'm creating a hot folder on a Linux VM that would automatically process any files put in there. I'm accessing it through NFS. Ideally, I want to wait for the files to finish writing, then do things with it, and move it to another directory.
Currently, I just use systemd to watch the directory but it didn't wait for the files to finish writing.
It just crashed my system because it moved the file too fast and triggered some reference check error (probably race condition). NFS is a low-level thing, so that's bad.
Hmm I don't think that this approach with checking for currently opened files can work, you will have some files opened in the append mode by lots of apps and you will never get them synced that way
I guess it depends how deep you want your sync, if its just user files then maybe it could work, but still I dunno how to do it too
Even on NFS, rename is atomic. So, write the files into the correct directory but with a .tmp name, then close the file, them rename it to remove the .tmp - and have the process that's picking up new files ignore ones with a .tmp extension
Hmm, that can work. But I won't be able to just drop files in the folder.
Maybe I can watch for certain events using https://pypi.org/project/inotify/
But I won't be able to use systemd and simple bash script for this
Anyone have a recomendation for a good OpenCV course? I found a free one on Udemy and got down using the basic .xml sets that come with the library, but I feel like I will need to make my own data sets for what I want to do.
Maybe I just need to use the docs at this point?
well yeah it would be a good idea to check out the docs too
there are some really good tutorials on youtube about OpenCV too
Cs50
@unkempt rock this server is specific to English, please keep that in mind.
@unkempt rock this channel is specifically about python, we have off topic channels such as #ot2-never-nester’s-nightmare if you want to ask about things unrelated to python
!e I thought the loop variable for a for loop had its own special scope rule, but apparently not.
print('before the loop')
for letter in 'abc':
print(letter)
print('after the loop')
print(letter)
@boreal umbra :white_check_mark: Your eval job has completed with return code 0.
001 | before the loop
002 | a
003 | b
004 | c
005 | after the loop
006 | c
nope, doesn't apply to with either
could the exit behavior of the with block cause whatever the with-variable was to have undefined behavior after the block?
x = lambda value : [k for k, v in MyDict.items() if v == value]
liste_allValue = [(y:=x(v)) for k, v in MyDict.items() if k not in y]
By curiousity why this code is wrong and how I can correct it (I try to learn how use the symbol := in python) ?
y is not defined
remember to use snake_case for your variable names. But in what way is this code wrong?
not undefined, but it'll have had __exit__ called on it
so, potentially insecure behavior?
My interpreter say NameError: name 'y' is not defined
"insecure" in what sense?
So I try to understand why
I guess I'm not entirely sure.
this is a channel for discussion of the language itself. you can try #❓|how-to-get-help
!resources this isn't really the channel for that
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I don't need help I just want resources to correct my self and see where I am wrong
I've seen lots of context managers that do very wrong things if __enter__ gets called twice. Like
manager = SomeThing()
with manager:
with manager:
pass
I've also seen plenty of context managers that do very wrong things if you try to call methods on them before __enter__ - at least as many as I've seen that will do bad things if you call methods on them after __exit__
anyone know whether there's a good way to type a function as pure in python?
there's not AFAIK - typing focuses only on the parameter types and return types.
ah, that's a little unfortunate
I have actually used the variable returned by context manager like this
with context_manager() as ctx:
...
if ctx.has_some_condition:
...
If context manager suddenly have its own special scope, I'll have a lot of broken codes 🤣
i've used this too
This one is more concerning though:
# have some items
for item in [1, 2, 3]:
print('ITEM:', item)
print('LAST ITEM:', item) # This will work fine
# No items
for item2 in []:
print('ITEM:', item2)
print('LAST ITEM:', item2) # This will break
might add a break and an else for those cases
!e
# No items
for item2 in []:
print('ITEM:', item2)
print('LAST ITEM:', item2)
@boreal umbra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | NameError: name 'item2' is not defined
😮
for item in maybe_nothing:
something
break
else:
item = None
remind me, when does else get entered, formally?
when you don't break
if the loop exhausts the iterable
so, no break and no return and no exception thrown
so if you break during what would have been during the last iteration, you don't enter the else, because it gets entered exactly when StopIteration is raised?
right

it's a common idiom when you're looking for something
and you break when you find it, and else is for the cases you don't find it
didn't guido say he wish he hadn't added it?
maybe
the else block for for loops?
i like it
he also said he regrets static methods, and I like that that option is there even if I don't use it
I use it more than the else block for try, heh
i use the else block in try a lot --- i try to have just the single line i think will error in the try and in rest of the relevant code in the else
I use it occasionally, though I find that an early return is usually more appropriate
I'm glad it exists, but I don't use it terribly often.
#Python optimization news: Inline caching has been a huge success. In 3.9, access to builtins and globals had sped-up considerably. In 3.10, regular attribute access and access to slots are also faster. Most everyday Python programs will benefit. This is a huge win.
260
That's rather nice
3.10 is shaping up to have a lot of improved syntax errors, too
It should do a much better job of actually explaining what you got wrong in a lot of cases
Let us say there is a while loop, is there a method that jumps to the next iteration? Not break as it breaks out of the loop but I just want a method that immediatly starts the next iteration of the loop
continue
k ty
wait how about a double continue?
like a for loop in a for loop, and a want to continue for both loops
how do u do that?
boolean flags, most likely 🙃
Set a flag?
ugh
This should be in programming 101
but i'm lazy as frick
and I don't wanna set a flag
Tough luck, lol
i wanna see if there is a faster way
even though if finding the faster way takes more time
uk what I mean lmao?
You can directly manipulate the iterator?
There's no purpose built way to continue an outer loop, but if you're leveraging functions properly then you almost certainly don't need to to get the desired behavior.
huh?
the iterator woudl just be for i in range(25)
like that
hwo would u directly manipulate the iterator?
Well, it is a tad bit more complicated after I thought about it. I was thinking of advancing the iterator but that's a C++ feature lol
hi need help in opencv terminology to segmentation of lungs image
Not the correct channel
Maybe try visiting computer vision specific channel/server
i tried to but cant able to fetch info similar to that
if you know kindly ping the server/channel so i can join there
@tidal marten Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
Uhh... mod?
thanks a lot
@tidal marten I understand that your intention was good, but in that case you can contact us so that we can repost it or whitelist altogether. Circumventing our filters is not appreciated
Yeah, sorry
Does anyone know how to properly configure pycharm to give proper code suggestions for libraries?
I keep getting errors like this
Cannot find reference 'CascadeClassifier' in '__init__.py | __init__.py'
I have the interpreter set up properly for my venv and I do get function suggestions for numpy
lol
I just figured it out
before I was just doing import cv2 but when I switched it to from opencv_python import cv2 it worked.
The answer came to me as I was trying to formulate my question hahah
My environment is now complete, feels good man
oof, that broke the import though :/
back to the drawing board
I feel like the solution has something to do with the __all__ thing in __init__.py but I just didn't understand what was going on there
Ok, this is so weird. Why would from opencv_python import cv2 even fix the Cannot find reference 'CascadeClassifier' in '__init__.py | __init__.py' problem?
even though its the wrong way to import cv2
This doesn't make sense to me. If you want to continue the outer loop, you're effectively discarding the state of everything inside, yes? So when you continue the outer loop the notion of continuing the inner loop no longer makes sense
I'm trying to setup mypy in my workspace, for my django project... Should I use the config in the user folder or my workspace?
Why were the keywords await and async made builtin, but asyncio is just stdlib, rather than a builtin?
wouldn't it make more sense if they already added the keywords to make whole asyncio a direct builtin
You can use alternative async managers, not just asyncio
I'm assuming that's why, async and await let you work with async in general, asyncio is a particular event loop implementation
async await are keywords, it is a parsing rule, you can’t import those
@atomic egret As 63n6h16 6ukrh4n said, asyncio is not the only event loop provider. There's also trio, for example.
Besides, a module in the stdlib is just a way of structuring the language. sys, threading, iteratools, and os are essential tools, but they're separated into their own modules, because bloating the already huge bulitin namespace doesn't help anyone.
well asyncio is a lil more than that
it also provides all the coroutine handlers in the first place
yeah
since they removed the ability to directly set the coroutine wrapper
which honestly i think is a lil annoying
Doesn't really make sense to export asyncio names to the builtins anyway, the await keyword is important to signify a possible context change which couldn't really be done without one
well, it could -- it was done with yield from, but that's just a bit meh.
Yeah, coroutines are essentially glorified generators
Well that's still a distinct keyword, if it was handled through a func for example it's be weird and not as noticeable
yeah, that does make sense, although it is a little weird to have these keywords without any default implementation for them
good example is the gevent system
asyncio is the default implementation
but bearing in mind most languages dont provide a default system where its exported directly like that
as far as im aware JS is the only system that does it because the language is built around it
Well, in JS, everything is avaiable in the builtin scope (in classes), because until recently it had no module system, and there are no built-in modules
I mean yeah
but JS was built entirely around the eventloop due to rendering design with browsers
JS' eventloop is an amazing example of making a language incredibly performent from the idea of the event loop
so I am in the inner loop and I want to continue the outer loop
for i in range(10):
# logic pre loop
for j in range(10):
if j % 2 == 0:
break
# logic inside loop
else:
pass # logic post loop
``` you can build a construct like this instead. using the `for-else` on the inner loop guarantees the loop executes extra logic only if no break was encountered, and you can just break the inner loop when the condition is met.
waiiiiit for else is a thing?
Now having said that, i personally just find the option of using a flag easier to read, but this is an option if you wish to avoid flags. Note that the core theme is, instead of worrying about forcing a continue from inside the loop to outside, we simply switch to executing logic only when condition is never met
oh yeah. for else is a syntax. the else is executed if and only if there was no break while iterating. (or rather, to be specific, if the iterator gets exhaused without breaking)
k, tysm! the more u learn 🙂
np 🙂
Need to be able to message some people. I am re-taking python again, and I just need to clarify certain things when I am programming. Thanks
Someone want to hop in a discord call with me and help me develop something
Using the Binance API?
Eh, I can't. Won't be useful.
Whoever asked me about type safety in C a while back, this is the article I was thinking about:
https://thephd.github.io/your-c-compiler-and-standard-library-will-not-help-you
and I realize now I made a mistake in talking about static types
@desert peak I actually read this today!
Wasn't a big fan of the writing style, but enjoyed the links to the various resources they had.
Heres a question: does calling logging.debug(debugdata) cause any performance issues if the logger isn't listening to debug calls.
It has some performance impact.
You'd have to profile to find out if the impact is enough to cause issues.
OK perfect I figured, and profiled it but just wanted to make sure it wasn't something else.
Every call still needs to access the logger and ask it if it's handling debug logs. That's not super expensive, but it's not free either
Yeah it adds up on a pi with hundreds of times a second XD
If you're worried that creating the debug data that you want to log is expensive to create, you can use an if statement to get the current logging level
This sounds like a great question for #data-science-and-ml
I'm guessing the if is going to have negligible performance impact compared to just deleting it?
Negligible hahahah
If the cost of the if statements is still prohibitively expensive, which you'd need to profile, then you'd have to delete them.
Yeah look I think going ham and deleting them is gonna be the way, they're not useful. Relics. Relics I say!
I don't think they will be expensive though.
Mmm. We enable/disable debug with a variable anyway so using it in an if is totally doable.
There is actually such a variable built in to the language
Logger.debug?
Ah. Yeah we look for an args and set logging.debug if we want it. My guess is that sets that value true
The debug value that I just mentioned is part of the language.
You actually can't overwrite it
Hmm.
@supple geyser @limpid marten this is not an on-topic conversation for this channel. Please refer to the channel description.
I'm working with type hinting and I have a function that takes a python module, is there a module object that I could use to type hint that?
There's types.ModuleType
and what about a whole package?
I don't think python uses a different type for them
The top-level module for a package is still a ModuleType, do there's no distinction as far as typing is concerned
This is strictly a discussion channel. I'm not sure what Numba is but perhaps you could ask in the topical channel that relates to it.
This is strictly a discussion channel. I'm not sure what Numba is but perhaps you could ask in the topical channel that relates to it.
@boreal umbra is baaaaasically Cython for numpy
A JIT compiler for certain types of numeric code
i guess 634 is going to be voted on soon and thats why the mailing list has new drama on it?
Is that the patma pep? What drama?
It appears to have some AOT capabilities too, which I wasn't aware of.
hm, I wasn't either - but I've never used it myself.
In a code :
a = 9
b=9
c = a + b
print("c")
How will the python know the arithmetic operation that you're using ? How will it evaluate?
Do you mean print(c)?
a + b basically calls type(a).__add__(a, b) and returns the result, unless it's a particular object - NotImplemented. In that case it falls back to type(b).__radd__(b, a) (a "reflected add") - if that returns NotImplemented a TypeError is raised, otherwise the result is returned.
Hoe does it know what is the add i wanna know the first source of this operator
How does it understand?
the type defines its own __add__ operator.
!e ```py
class A:
def add(self, other):
print(f"adding {other} to {self}")
return NotImplemented
class B:
def radd(self, other):
print(f"reflective adding {self} to {other}")
return NotImplemented
A() + B()
@raven ridge :x: Your eval job has completed with return code 1.
001 | adding <__main__.B object at 0x7f9ce6e36fa0> to <__main__.A object at 0x7f9ce6e36fd0>
002 | reflective adding <__main__.B object at 0x7f9ce6e36fa0> to <__main__.A object at 0x7f9ce6e36fd0>
003 | Traceback (most recent call last):
004 | File "<string>", line 11, in <module>
005 | TypeError: unsupported operand type(s) for +: 'A' and 'B'
i dont understand , im new to coding
Have you learned object oriented programming yet?
Operators like + - * / % ^ & | are baked into the language, you can't define your own, if that's what you're asking.
Like everything else in Python, you can find the implementation somewhere here: https://github.com/python/cpython, but it probably won't be of much value if you're just starting out.
ok
unless you've learned OOP, it won't be possible to explain how + works in terms that make sense to you yet.
words like type and object just don't mean something concrete to you yet, and there's no way to explain the behavior without those.
k
Still super controversial and people want it canned
TIL typical method/signature arguments are Positional OR Keyword and that you can refer to ones, even without a default argument through kwargs.
It's not until 3.8 that we can specify positional only
Specifying **kwargs in the signature allows it to accept abitrary extra keyword arguments
Mind blown
anyone knows how to read a map file in python.. with open(mapfile,'r') as fp:
This code is giving error
I disagree
+ is just a function call - that's pretty easy to understand
1 + 2 -> add(1, 2)
all of our special symbols are just sugar at the end of the day
But that does not really explain how they work in Python
it does, tho
The part @raven ridge is referring to is that you can implement the functionality for those operators; it's defined in the types
When you're doing something like a + b, Python will first try a.__add__(b) to seek for an implementation in the type of a
it doesn't take type theory to know that classes have methods
I don't think it was meant much in that way, but to really understand how those operators work in Python, you'll get in touch with implementation special methods rather quickly
just scrolled up and saw that person is new to coding entirely
And that's the OOP part: The implementation of the operators depends on the special methods defined in Python's data model
overriding dunder methods is pretty advanced for a newbie, I agree
I didn't say it does. But if you don't know what "type" and "method" mean yet, you do need to stop and learn that before someone can explain to you how + works in Python. Every answer that's deeper than "it's built into the language" requires knowing that objects have types, types have methods, and + calls a method of each of the operands' types in turn to ask if they know how to add the two operands together. There's no way I can see to simplify it further than that.
yeah - but that function behaves like: ```py
def add(a, b):
ret = type(a).add(a, b)
if ret is not NotImplemented:
return ret
ret = type(b).radd(b, a)
if ret is not NotImplemented:
return ret
raise TypeError
im trying to place files and a directory I created.. how would I ?
@neon palm #❓|how-to-get-help this isn't a help channel
I kind of wish for a statically typed Python
Probably a Python front-end for LLVM, lol
Why does python use a special value instead of an exception for this?
My gut says performance - it definitely is faster to compare against a singleton using is (well, pointer equality in C) than to check whether an exception was set and, if so, whether that exception was a specific one (or a subclass of that one?). I don't know whether that's actually the reason, but I suspect so.
But it's definitely a bit weird, and doesn't quite fit modern Pythonic sensibilities.
And, worse - there's both the NotImplemented singleton which requests a fallback to the reflected operator, and the NotImplementedError exception class. People mix these up all the time; it's a real footgun in the language.
That's why I was not able to raise NotImplemented
I thought NotImplemented is just a shorthand for NotImplementedError()
:incoming_envelope: :ok_hand: applied mute to @merry pewter until 2021-02-08 06:16 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Ooh, very cool, never heard about NotImplemented singleton before.
As for language design, in general I think it's okay for language designers to use footguns as long as programmers don't have to. I think some of it is unavoidable, and some of it is practical
This might not be exactly on topic, but which percentile numbers are useful when comparing thread performance based on thread count?
I ran my threaded code at least five times with five different thread count. I included the initial cold run though.
What do you mean?
This is thread performance in Python?
Yeps
My machine is 2c/4t so that might explain the sweet spot on 4 threads
I did have some mutex locks as well as IO operations
while on topic of threads
what is the point of threads
wait i answered my own question while asking it
is the point to do things parallel when you need the results at the same time?
but then again, if i do some sorting algorithm shenanigans, and i put them into 2 threads, they are gonna take as long as if i put them behind each other, right?
if i wanted SPEED i'd use multiprocessing
Threads in python should only be used for IO bound tasks.
...or for CPU-bound tasks that lift the GIL, like some stuff in numpy and PIL
Most io bound tasks are mostly taken care of by async, but it can't handle anything that's blocking. Sometimes with a cpu bound workload you do need the concurrency, but processing parallelism isn't important which is a great use case for threads. async would stall at the cpu bound workload, and multiprocessing would add unnecessary overhead
for tasks that dont lock the GIL, threads may be faster because they're lighter than processes
I'd say most thread uses in python now are through out of python gui libs, extensions that can do work without holding the gil and executing blocking tasks while working with async
but don't processes run on different cores at the same time like
ab
ab
ab
ab
while threading is just ababababababa
however, i find myself that in python its mostly multiprocessing or async
will multiprocessing code even run on non-unix machines
i think youre right in case of python specifically. im not a 100% sure though
iirc there was something like that
python has to let the python interpreter manage threads, so i suspect it's the case
Without synchronization it may do things like aabb etc., as the threads will request the gil after a certain amount of time (5ms I think) and the thread that's currently holding it will have to release it
ok just looked it up it only doens't run on mac
But yes, it'll be serial in the sense that only one thread will ever be executing your python code no matter how the os manages them
Ok so pretty much
this is a question
my code worked fine
2 seconds ago
i didnt adjust it
i just closed the running test
and now it wont show the gui
and wont show any errors
The limitation that the GIL imposes is that two threads can only run instructions at the same time if one of them promises not to run any Python bytecode or call any Python functions. It can still do other stuff, like crunch numbers or encrypt data or whatever. It's a big limitation, but plenty of libraries work around it.
i understand, thank you! amazing
hey folks, how would you enforce a factory method for a type over its constructor?
I need the ctor due to inheritance, but it leaves the class in an invalid state
obviously documentation is one way, but is there a way to detect a calling class method and throw an assertion error?
Can you elaborate on the "due to inheritance" bit?
class T(V):
def __init__(self):
super().__init__('param')
@classmethod
async def create(cls):
return T()
super dumbed down example
if you omit that ctor, the ctor of the superclass gets called anyway
my class members require async fn calls and can't be used in the ctor
I'm passing parameters to the superclass
ah
for reference, I'm extending one of fastapi's oauth2 schemes
to work with an internal security implementation
Why not:
class T(V):
def __init__(self):
raise TypeError("call create")
@classmethod
def create(cls):
obj = object.__new__(cls)
super().__init__(obj)
return obj
was about to type that
because I didn't know that pattern 🙂
will super() work in a classmethod
the two arg form definitely will
I would also suggest erroring out __init_subclass__, since extending this class won't work
my main goal is that you are forced to use the factory method
so my coworkers don't ignore my documentation and do something dumb
If you keep the constraint that create must be called, and subclasses create calls the super create, it should work.
Though multiple inheritance won't.
class T(V):
def __init__(self):
if not getattr(self, '__proper', False):
raise NotImplementedError('use the factory method make to create an instance of this class')
super().__init__()
@classmethod
def make(cls):
t = object.__new__(cls)
t.__proper = True
t.__init__()
return t
``` would let you keep a ctor, so subclassing will work even if a ctor is used
and missing a supercall to make would also error out
does super() work in any method call?
I thought it was restricted to ctor for some reason
only place I ever see it, I guess
it works in any method
!e ```py
class A:
pass
class B(A):
def init(self):
raise NotImplementedError("call create()")
@classmethod
def create(cls):
obj = object.new(cls)
super().init(obj)
return obj
class C(B):
@classmethod
def create(cls):
obj = super().create()
obj.attr = 5
return obj
print(C.create().attr)
print(C())
@raven ridge :x: Your eval job has completed with return code 1.
001 | 5
002 | Traceback (most recent call last):
003 | File "<string>", line 18, in <module>
004 | File "<string>", line 5, in __init__
005 | NotImplementedError: call create()
hmmm it doesn't like that
subclassing seems to work fine with my approach.
Hello i need some help iwth the ursina game engine
k
what's the form to call the ctor with super? I thought it'd be the same calling semantic as the super ctor
what's the name of the class this is in?
JWTBearer
then, try super(JWTBearer, scheme).__init__(scheme, ...)
yeah, it does work if you use create instead of __init__
my method should in theory allow the use of __init__ in a subclass
I feel like I'm going crazy. New error lol
unexpected arg it tells me
I never do any subclassing in python, always lose my way
test is better than screenshots - what arg is it saying is unexpected?
and OAuth2PasswordBearer.__init__ does take tokenUrl as a parameter? Hm.
yep
!e ```py
class A:
def init(self, arg):
self.arg = arg
class B(A):
def init(self):
raise NotImplementedError("call create()")
@classmethod
def create(cls, arg):
obj = object.new(cls)
super().init(obj, arg)
return obj
print(B.create(5).arg)
@raven ridge :white_check_mark: Your eval job has completed with return code 0.
5
seems like it should work...
is this a linter getting confused, or the interpreter itself raising a TypeError?
about to check. intellij has been flakey in these kind of scenarios
nope, get an error at creation
oh weird
"got multiple values for argument tokenUrl"
uh - ok. so it thinks you passed two values for it, probably one positionally and one by keyword?
yeh
What's the signature for OAuth2PasswordBearer.__init__ ?
I get rid of the first arg and highlighting goes away...
ah, yeah, that seems right.
the __init__ is already bound to an object by the two-arg super call, so you don't need to pass that argument again.
So it should be correct to do ```py
super(JWTBearer, scheme).init(tokenUrl=token_url, auto_error=False)
ahhh, makes sense
I wish super was documented better
they literally point at some blog to see its semantics in the docs
the other day I was trying to figure out multiple inheritance and gave up
yep, that's the link in the docs
no where in that entire post do they use super with args
ah. I don't know of anything that explains it better than that - that's written by one of the CPython core developers.
I understand super gets the superclass, but I wanted more granular control which is what I understood the arguments to grant
just wasn't sure how
it doesn't get the superclass, it gets the next class in the MRO
which may be a superclass, or may be a sibling class.
not necessarily
even if you've only got one parent class, if someone derives from you then it's possible that a call to super() from within your code will call a sibling class rather than your superclass.
that bit's going a bit over my head atm
I've been staring at security documentation all day so I'm a little fried 😅
e.g., if you've got: py class A: ... class B(A): ... class C(A): ... then a call to super() in either B or C will delegate to A, just like you think it will. But if someone comes along and does: py class D(B, C): ... then calls to super() inside a method that D inherited from B will delegate to C, not to A.
oh, interesting
which I'd consider correct behavior, but yeah, confusing
at first glance
!e ```py
class A:
def meth(self):
print("A meth")
class B(A):
def meth(self):
print("B meth")
super().meth()
class C(A):
def meth(self):
print("C meth")
super().meth()
class D(B, C):
pass
print("On B:")
B().meth()
print("On C:")
C().meth()
print("On D:")
D().meth()
@raven ridge :white_check_mark: Your eval job has completed with return code 0.
001 | On B:
002 | B meth
003 | A meth
004 | On C:
005 | C meth
006 | A meth
007 | On D:
008 | B meth
009 | C meth
010 | A meth
Isn't the general philosophy one of composition, not inheritance, these days?
it's generally more maintainable in most cases, but inheritance, even multiple inheritance, has its uses if planned carefully.
so in my example, super(JWTBearer is resolving OAuth2PasswordBearer?
yep.
is there a way to specify a concrete class?
just calling the class's __init__ with self = scheme?
yep
super(cls, obj) scans obj.__mro__ until it finds cls, and then returns a proxy to the next class in the MRO after that.
super is specifically to avoid specifying a concrete class, because you might even not know it
so given an object with an MRO of [D, B, C, A], super(B, self) will find C.
I wish there was a Self alias like Rust has
Right - if you try calling the superclass that you know about directly, you may skip over a class in the MRO unexpectedly, never giving it a chance to initialize itself (or hook whatever other behavior)
The most confusing thing about super is its name. It sounds like it looks up the superclass. It doesn't. It looks up the next class in the MRO, which is frequently but not always a superclass.
yes, the source of my frustration this week
I'm glad this forum exists, this community is great
side-note: why object.__new__?
because init will throw?
This seems useful as a plug-in system....
Then again, there’s pluggy
also: is there a good solution for async destructors?
I guess getting the event loop and calling functions that way?
make it an async context manager?
idt you can rely on any globals existing when destructors are called
the context is that I have a session that lives on as an attribute on my class, and I want to ensure that session is closed, but the close method is async
!ot @eternal forge
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please don't spam random images in on-topic channels.
patma is accepted!
<#mailing-lists message>
i.e. PEP 634, PEP 635, PEP 636
hnnnnng
python finally gets its 1990 feature of switches
(kidding, of course)
oh wow, they might even have them in time for py310
that makes me very excited for next year
Well, Haskell had pattern matching (not like switch), in 1990s, so technically you're not wrong!
ugh, going insane. how do you finalize an async attribute? aclose doesn't do it, not allowed to use await in __del__
the event loop seems to already be closed by the time __del__ is called
so I'm leaking connections when my app finishes
You can't await in __del__ because there's no guarantee about when and where __del__ gets called. It could get called in a thread that doesn't have an event loop, it could get called after the event loop has been closed, it could be called after the __main__ script has finished. Technically it's not guaranteed to be called at all, in fact.
there was talk for a while about moving all garbage collection into its own thread - hasn't happened, but it could.
sounds like you should probably be counting on a context manager to free up resources for this, rather than __del__. async with, that is.
if I did, I'd end up starting up a new sessionpool on every request
Sounds like the session pool should be under the user's control, and they should pass it into you, then.
the pool exists so I can query my adfs infra for new keys
it's entirely internal to the class
Then yeah, you'd need to create a new pool on every call.
You can do something like keep a reference to the event loop that you were created with and use it for scheduling a callback with call_soon_threadsafe from __del__, maybe. But ew.
Someone in #async-and-concurrency might have better suggestions.
yeah, after more thought, an extra sessionpool every few months isn't impactful enough to engineer a solution around it
All hail the overlord pattern matching
ML had patma in the 70s, and math had it even earlier.
I can't if there's going to be a new dunder or not
__match_args__
I saw it's on there for namedtuples and dataclasses but can't find anything about it being an official dunder
that's the thing with duck typing, it doesn't matter what's official!
Like theres dunders related to say abc that don't do anything unless you use that meta
Idk about that
def __iter__, I'm an iterator now!
That's bc for loops and stuff know to look for it
I swore I saw a deferred idea about it
Q for anyone: does python cache module execution?
using python -m app gives me different results from uvicorn app.main:app
even though the code is the same
going. insane.
false flag: intellij is dumb
does that mean you solved it?
I did. IntelliJ left a zombie process that kept the port bound, but rebinding that port didn't give me an error or anything @spark magnet
but also didn't update my web server
Am I seeing that the patma pep was accepted today?
yep
I haven't looked at very many patma examples but I'm scared that I'm going to be disappointed by all this
Calling IntelliJ a Java IDE is like calling VSCode a JavaScript IDE
Well, I personally don't find it absolutely disturbing like some people's reactions come off.
But I guess you can't really form an opinion before you actually use the feature extensively.
people are insufferable and loud people averse to change usually win those arguments because they're so insufferable
well, patma was accepted despite loud people
Maybe I don't find it disturbing because I have used a little bit of Haskell
if you're familiar with anything that has real pattern matching, it's dreamy
not just switch statements
in rust, they are very powerful
You can always try VSCode 🙂
what do you mean by that?
You can use mypy as a type checker as well
do... do you use the default LSP?
Jedi is at least tolerable, but Pylance was a great jump in experience for me
er, Microsoft*
Jedi was the crappy one
I'm using Pylance
Yeah, I work at a big place, no plugins unless they go through procurement
oh wow
for whatever reason, the task runner in intellij is ignoring my fastapi dependencies. the plot thickens but honestly, I'll just go back to console debugging instead
Nuking .idea/ from orbit seems to have resolved everything
but..but..your workspace configs 😦
I'm dying with my IDE problems tonight
Interesting
I really want to see better patmat examples. Reading the peps is too abstract
!pep 636
I feel like this is a lot of syntactic sugar
How long do you think it'll take anaconda to get it's hands in it
Conda is still on 3.8
I guess there aren't too many examples of how patma could improve code, because library writers wouldn't design stuff so that it looks and feels ugly, so they choose other, less optimal (for the given problem) approaches (like subtype polymorphism instead of a switch).
For example, this function https://github.com/decorator-factory/python-fnl/blob/master/fnl/fnlx.py#L37 and this https://github.com/decorator-factory/python-fnl/blob/21a1a67d20eeb20f3c09dfa7e9de758c4914bd36/fnl/bindings.py#L133
and https://github.com/gurkult/py-gurklang/blob/master/gurklang/prelude.py#L538 (and many functions in that project) could all be improved by pattern matching. Basically, everything that deals with parsing or language evaluation or otherwise interpreting a tree.
Oh gosh, DIY pattern matching looks awful
yep 🙂
Man people at work accuse me of writing too complicated of shit at work and then I see that stuff in repos and like ???
well, that's a bit of an esoteric bootleg
I wouldn't use that in actual production code
Yeah
How would you write that function without pattern matching, though?
Which one?
The first one
People at work want to stick to strictly procedural with lots of type checks, like some weird java or c#
Probably with a lot of IFs and isinstance/issubclass
I would say that even my horrible bootlegged pattern-matching is more readable
the with thing? Yeah, a few function calls.
yeah, it's a combination of pretty obscure things
Maybe instead of using string, you can create some representation classes and evaluate the input against that?
Still a lot of overhead though
Well, in this case, it's not a very high-load system
Pattern matching is better than if chains in these cases because it shows the structure that's expected instead of running explicit checks. In other words, it's more declarative.
This: https://github.com/gurkult/py-gurklang/blob/master/gurklang/prelude.py#L538 is probably a very good example (that I showed previously).
Although... that probably wouldn't be fixed by patma, lol
Idk, I also have some distaste with languages that do weird syntactic stuffs. Probably why I dislike those kind of things.
What would be a good coding project? Easy to code(as in not to difficult for a beginner), but a cool program
languages that do weird syntactic stuffs
Like what?
The one thing I know is how Angular do dependency injection through the constructor, also some Kotlin and Dart stuffs
Anything that is not traditional like C/C++ lol
Well, that's just an issue of familiarity, maybe
Bash is the language with the most cursed syntax and semantics I've ever seen.
yet people are able to use it to do some actual stuff
Yeah, I just have to overcome that first "eww" instict
Bash doesn't have to be pretty though
Well, it just has very confusing control flow constructs IMO
My problem with the newer languages mostly stems from the barrier to entry, not from scratch, but if you already have experience with other languages
Last year I just looked into lots of different languages at least at a very superficial level (the tutorial): C++, Clojure, Rust, Haskell, OCaml, Agda, JavaScript, TypeScript, Elixir. maybe something else. After seeing lots of different, sometimes completely alien, things I'm a bit more open-minded about language features or just how they look.
I even liked some parts of JavaScript
Anyone got good applications of context managers that arnt insane?
Or that are useful but not the typical use case
I use it to rollback data in a class if there's an Exception lol
@swift imp contextlib.suppress uses exception swallowing (which was a new thing for me) to suppress exceptions.
Tbh Javascript and PHP are probably decent languages if not for the bad APIs 😅
I feel like exception handling is a normal use case though
Maybe I should try PHP.
Not that I don't appreciate your responses
It's mostly used for Exception handling though
Closing resources gracefully
Is monkeypatching a non-typical use case for you?
Testing libraries use context managers to temporarily patch module or class members.
@swift imp
Oh, I remember -- typing in discord.py
https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.typing
Basically, it allows you to put some code inside async with bot.typing():, and while that code is running, the bot is displayed as typing...
That's neat
@grave jolt :warning: Your eval job timed out or ran out of memory.
[No output]
Well, you might have missed that, but the bot uses it to signify that code is being executed.
!e
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Re. people mistaking the topic of this channel, has 'language-discussion' been suggested as an alternate name?
i think a variant of that was used before
You won't believe how many names we have tried.
It's hard to make a good name, and it's always a compromise.
Like how #unit-testing isn't just about unit testing.
It was renamed because automated-testing attracted selenium questions about webscraping.
(one of the reasons)
I got the sense of that. Figured I'd see if that name in particular had come up before.
That is new and confusing knowledge re. #unit-testing
@magic hedge Another example is how it's #async-and-concurrency and not #concurrency-and-parallelism because it just doesn't fit
or how it's #c-extensions, even though you can also write extensions in C++, Rust, Forth, Fortran and probably many more languages
we might also try another name for #software-architecture, because people confuse it with graphic design
Forth? 👀
hypothetically speaking, I haven't actually seen it used for extensions
Fith?
Do each of those languages have their own equivalent to the C API, or just proxies for it?
Rust has a FFI feature https://github.com/ijl/orjson/blob/master/src/ffi.rs
Not sure about Forth/Fortran, but it should be possible somehow
Cheers
very little of Python's C API actually requires C. Most of it is a C-callable ABI, which can be used from any language that can call C functions.
Could muddy the waters of 'design' by shifting to #language-design
That makes good sense
a handful of public interfaces actually are macros, which really do require a C compiler - those are the exceptions.
In the end, it's just pushing around bytes, right?
Back to assembly we go!
well, let's see. You need to be able to create a dynamic library (.so or .dylib or .dll or whatever). That dynamic library needs to expose a C-callable symbol named PyInit_<modulename>. That needs to define a structure in a particular memory layout, and call some C functions exposed by the interpreter (which could be found through dlsym or the like)
Is there a min and max version for compatible C standards?
AFAIK CPython supports every version of standard C
the first C standard was C89, and lots of programs are still written for C89 compatibility.
I think the recent versions now require C99?...
ah, you're right. https://docs.python.org/3/whatsnew/3.6.html#build-and-c-api-changes
Doesn't trying to get patma into 3.10, just having accepted the PEP today, seem a bit last-minute? From what I can see the first 3.10 beta has it's expected release in May, which seems pretty soon to get everything in by.
I guess they do already have an implementation and have been working on it for a while though
No major implementation can be added in beta, so I don't think we will have it to 3.10
In the thread they posted accepting it, https://mail.python.org/archives/list/python-dev@python.org/thread/SQC2FTLFV5A7DV7RCEAR2I2IKJKGK7W3/, it says
We consider that the presence of such
high-quality documentation must be present on the first release of Python 3.10, and
therefore its absence should be considered a release blocker
Surely if there's documentation being released for it it will be implemented as well, no?
the whole match statement stuff seems rather rushed
not entirely sure what they're doing tbh
Adding code that's easy to write and hard to read.
I love pep636, it's very well written, and yet it's still hurting my brain trying to imagine walking into a code base blind and seeing pattern matching.
I think I'll need to spend some time reading the links fix error shared above when I get a chance.
should i use excel i am trying to track my expenses in python from another document
im on mac
Isn't that true for just about any new big addition, like async/await or type hints?
Besides, it will take years to put pattern matching in widely used libraries and business apps, so you'll have time to adapt.
I have yet to see the walrus in prod app tbh
well, walrus is a rather small addition
I could totally live without it, if the time dedicated to it would be spent on patma bikeshedding, or subinterpreters, or something else
From #help-donut , what is going on here?
In [11]: [5, 6] is [5, 6]
Out[11]: False
In [12]: id([5, 6]), id([5, 6])
Out[12]: (4363340736, 4363340736)
Hmm
The address (or object, not sure if there is an optimization) can be reused after the lists are dereferenced
the is check needs both alive, id only keeps the current one
What is the dis for the latter?
should be build list and a call to id twice, both of which are completely separate
While the first one has to build both lists and then compare
Ah that makes sense
In [16]: id(list(range(5, 7))), id(list(range(5, 7)))
Out[16]: (4362631488, 4362631296)
Doesn't really happen when list literals arent used
...which leads me to believe its an optimization?
I don't use it in prod because I keep forgetting we are on 3.8
Also ugh pattern matching
I should have said something on the mailing list
but that returns true for tuples though
I feel like I missed my chance to speak up
That certainly is one optimisation I'm aware of
Looks like PyList_New will use a free list when available from a buffer which are created on list dealloc https://github.com/python/cpython/blob/00d7abd7ef588fc4ff0571c8579ab4aba8ada1c0/Objects/listobject.c#L153-L156
Which would mean list() doesnt use PyList_New?
Ah yeah it doesn't, https://stackoverflow.com/a/55586595
The init is a bit more generic https://github.com/python/cpython/blob/00d7abd7ef588fc4ff0571c8579ab4aba8ada1c0/Objects/listobject.c#L2696-L2756
What is the dis for the latter?
!e
from dis import dis
print(dis(lambda: []))
print(dis(lambda: list()))
@boreal umbra :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 BUILD_LIST 0
002 | 2 RETURN_VALUE
003 | None
004 | 3 0 LOAD_GLOBAL 0 (list)
005 | 2 CALL_FUNCTION 0
006 | 4 RETURN_VALUE
007 | None
idk if that answers your question 🤷♂️
It's just trading one abstraction for another. I don't know if I've learned anything.
!e
from dis import dis
print(dis("[1, 2] is [1, 2]"))
print(dis("id([1, 2]), id([1, 2])"))```
@undone hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (1)
002 | 2 LOAD_CONST 1 (2)
003 | 4 BUILD_LIST 2
004 | 6 LOAD_CONST 0 (1)
005 | 8 LOAD_CONST 1 (2)
006 | 10 BUILD_LIST 2
007 | 12 IS_OP 0
008 | 14 RETURN_VALUE
009 | None
010 | 1 0 LOAD_NAME 0 (id)
011 | 2 LOAD_CONST 0 (1)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wubufesone.txt
not sure how dis can help understand the behaviour
in cpython there is an internal free lists array. when a new list is made (using the BUILD_LIST instruction) it can use a list from that free list, as the runtime knows the length of the resulting list by the time it gets to there. list(arg) uses PyType_GenericAlloc instead of PyList_New(size), then calls list____init____impl(list_obj, iterable) which handles putting the argument of list(arg) into the new list
basically, the reason why list(arg) doesnt use the free lists array is because it initializes the new list before it knows the size of the arg passed in
@unkempt rock ^ that is why
no, not really. We have the implementation ready, and already some people working on the documentation
so there is a really high (I'd even say it is certain) that we will have patma in 3.10
Isn't that true for just about any new big addition, like async/await or type hints?
These are much much smaller compared to patma. I'd say it is the biggest change in the last decade or so.
Oh that's cool
Yeah, that's certainly pretty big. Although it's more of a syntax change than a fundamental change of semantics, along with type hints and async/await.
btw, what's your opinion on patma?
That clears it up, thanks
Indeed
If I wanted to traverse through code without executing it would ast be the way to do it?
Yep.
there are other ways depending on what aspect of the code you want
So basically I have a few dictionaries, who ultimately get merged together into one, but for each dict I would like to know where each key is being populated last prior to final updating.
Basically the path through the code isn't completely determinant
At least easily
So I would like someway of seeing the intermediate steps without having to actively debug
Anyone here interested in writing python -> another statically typed language transpiler?
Except that it is against Teams’ ToS
Python to LLVM would be nice
that is already sorta implemented btw
It doesnt work for everything though due to python types
but if you have purely numerical calculations Numba can jit compile it to C code with LLVMlite
@topaz rune This channel is meant for discussing the language itself, check out #❓|how-to-get-help
@topaz rune No problem; you can always check out the channel description for each channel before commenting there for the first time.
Does python to rust to llvm work?
That honestly sounds like too much indirection
Similar discussion on why nim compiled to C and not llvm here:
Are you concerned about compile times or dependency on another language ecosystem?
More indirection means more chances to mess up some little details here and there
Rust is totally different from Python
Rust is more concrete and more restrictive than python. To make it work python is constrained to a small subset as well
I would start from the tests/cases and expected outputs to get a sense
I'm pretty sure it just emits LLVM IR, and then LLVM compiles it, places it in executable memory and gives you a function pointer to call it.
Python generally would be alot of pain to transpile to from python
Python uses ALOT of callbacks
and rust is a language where you generally dont have anywhere near that same amount of callbacks or non at all
can OrderedDict be used as a deque?
wat
rust makes liberal use of closures (callbacks)
Not in the same way python makes heavy use of it
it looks like OrderedDict.popitem(last=False) is equivalent to deque.popleft() and OrderedDict[key] = item equivalent to deque.append(item)
ig the question is why would you want a OrderedDict over a Deque to be used as a deque
can someone help me my code say some thing is wrong btw its my first code
from pyatuogui import *
import pyautogui
import time
import keyboard
import random
import win32api,win32con
#Tile 1 Position: X: 1019 Y: 471 RGB ( 1, 0, 1
#Tile 2 Position: X: 754 Y: 471 RGB: ( 54, 159, 198)
#Tile 3 Position: X: 840 Y: 471 RGB: (164, 221, 255)
#tile 4 Position: X: 934 Y: 471 RGB: (148, 178, 254)
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
while keyboard.is_pressed ('q') == False:
if pyautogui.pixel(1019, 471) [0] == 0:
click(1019, 471)
if pyautogui.pixel(754, 471) [0] == 0:
click(754, 471)
if pyautogui.pixel(840, 471) [0] == 0:
click(840, 471)
if pyautogui.pixel(934, 471) [0] == 0:
click(934, 471)
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Read this, don't press the trash bin
for search OrderedDict is faster
yeah in my use case all keys are hashable
I used timeit to test insertion on ordereddict, it took minutes, but in deque it's the search that takes minutes
search test
$ python -m timeit -n 500 -s "from collections import deque; q = deque(); [q.append(i) for i in range(1000)]" "[1001 in q for _ in range(1000)]"
500 loops, best of 5: 12.6 msec per loop
$ python -m timeit -n 500 -s "from collections import OrderedDict; q = OrderedDict(); [q.__setitem__(i, None) for i in range(1000)]" "[1001 in q for _ in range(1000)]"
500 loops, best of 5: 49.4 usec per loop
insertion test
$ python -m timeit -n 500 -s "from collections import OrderedDict; q = OrderedDict()" "[q.__setitem__(i, None) for i in range(1000)]"
500 loops, best of 5: 187 usec per loop
$ python -m timeit -n 500 -s "from collections import deque; q = deque()" "[q.append(i) for i in range(1000)]"
500 loops, best of 5: 74.3 usec per loop
The insert only being 2.5x slower isn't so bad, honestly
in my use case I do more seach than insert
If you have sample code to transpile to rust, please send me a paste/gist. I'll add it here:
What sort of coverage r we looking at STD lib wise?
It doesn't compile much beyond what's in the tests/cases directory. But if you're looking at examples on rosettacode, a lot of that should be mechanically transpiled between languages.
binit example is from rosettacode.
Coverage of stdlib: the harder problem is translating datetime.datetime.now() or uuid.uuid4() to another language. I'm thinking of some type of a plugin system where stdlib is transformed.
does that mean that PEP-636 was accepted? I don't get it
oh my god we will have pattern matching in py 3.10
that's great
Yes. There was a message on the mailing list as well.
Probably the most controversial and debated feature in Python ever.
it's only been a while since :=...
🥴
The stakes on this one are way higher. It's not hard to pretend walrus doesn't exist, but this one will be a lot harder to ignore
but only one of these two got the BDFL to quit
(it's a joke)
Realistically, that probably wasn't a bad outcome. I think the Python ecosystem is in a better place now.
Well, there are some very dedicated people, it seems 🙂
https://pypi.org/project/flake8-match/
flake8 plugin which forbids match statements (PEP 634)
And it's already up to 1.0!
I'm sure someone will fork CPython and make match segfault or something

