531 points · by bratao · 3y ago · 399 comments
However, there is also a bit of a struggle going on between them and the project to remove the GIL (global interpreter lock) from CPython. There is going to be a performance impact on single threaded code if the "no GIL" project is merged, something in the region of 10%. It seems that the faster Python devs are pushing back against that as it impacts their own goals. Their argument is that the "sub interpreters" they are adding (each with its own GIL) will fulfil the same use cases of multithreaded code without a GIL, but they still have the overhead of encoding and passing data in the same way you have to with sub processors.
There is also the argument that it could "divide the community" as some C extensions may not be ported to the new ABI that the no GIL project will result in. However again I'm unconvinced by that, the Python community has been through worse (Python 3) and even asyncIO completely divides the community now.
It's somewhat unfortunate that this internal battle is happening, both projects are incredible and will push the language forward.
Once the GIL has been removed it opens us all sorts of interesting opportunities for new concurrency APIs that could enable making concurrent code much easer to write.
My observation is that the Faster Python team are better placed politicly, they have GVR on the team, whereas No GIL is being proposed by an "outsider". It just smells a little of NIH syndrome.
I think it's too late to consider removing the gil from the main implementation. Like guido said in the PEP thread, the python core team burned the community for 10 years with the 2-3 switch, and a GIL change would be likely as impactful; we'd have 10 years of people complaining their stuff didn't work. Frankly I wish Guido would just come out and tell Sam "no, we can't put this in cpython. You did a great work but compatibility issues trump performance".
Kind of a shame because Hugunin implemented a Python on top of the CLR some 20 years ago and showed some extremely impressive performance results. Like jython, and pypy and other implementations, it never caught on because compatibility with cpython is one of the most important criteria for people dealing with lots of python code.
I don't see why. It's a much easier transition than 2 to 3.
Make each package declare right at the top if they are non-GIL compatible. Have both modes available in the interpreter. If every piece of code imported has the declaration on top, then it runs in non-GIL mode, otherwise it runs in classic GIL mode.
At first most code would still run in GIL mode, but over time most packages would be converted, especially if people stopped using packages that weren't compatible.
I think it'll happen one day. Is Python going anywhere?
Give it 20 years. The 2 -> 3 switch will be like the Y2K bug, only remembered by the oldest programmers. The memories of pain will fade, leaving only entertaining war stories. The GIL will still be there, and still be annoying.
Then, when everyone has forgotten, the community will be ready. For an incredibly long and grinding transition to Python 4.
I'm already in a state where I can't upgrade to the latest gcloud tools because 2.7 is removed from them. I'm stuck on a version from late last year until I've finished my ports or abandon my projects.
I was a very happy user of GAE standard for many many years, but they burned me in the end and I've learnt my lesson about building on proprietary tools.
Standard frameworks and standard databases for me from now on!
The GIL is hiding all kinds of concurrency bugs. If the CPython team default disable it then all hell is going to break loose.
It's better to carve out special concurrency constructs for those that need it.
As an early python programmer, I copy pasted these types of answers. My old threaded code absolutely has these bugs. I’ve even seen code in production that has these bugs, because they’re sometimes dumb performance enhancements, rather than bugs, unless you happen to use a Python interpreter without a GIL, especially one that that doesn’t exist yet.
Great care would have to be taken to make sure the GIL was not disabled by default, for anything an existing thread touches (or some super, dynamic aware, smarts to know if it can be disabled).
I think this is more an issue of popular packages were developed and tested against cpython and there wasn't enough effort available to port/test them against anything else. There's no special magic in cpython that Python programmers love, they just want their code to run. If they've got a numpy dependency (IIRC it doesn't support pypy but I'm not going to look it up so I may be corrected on that point this is a long parenthetical) they can't use an interpreter that doesn't support it. Even if it worked but had bugs it didn't have in cpython, they're still going to use cpython. Most people aren't writing Python for its super duper fast performance so they're fine leaving a little performance on the table by using the interpreter that their dependencies support. Whatever that is.
A core team led by him, which also had the opportunity to make much more impactful changes during 3, including removing the GIL, since they were going to mess up compatibility anyway, but didn't.
All that mess (and resulting split and multi-year slowdown in Py3 adoption) just to put in the utf-8 change and some trivial changes. It's only after 3.5 or so that 3 became interesting.
At this point, removing the GIL is such a large change, it would probably be better to wait for the end of (practical) performance to single-threaded code, and then remove the GIL. At that point you would have a community consensus behind the change, and the holdouts wouldn't have a stranglehold on keeping the community from moving forward.
I'm not sure if I would call the move from 2 -> 3 a trivial change, but maybe you're more well versed in Python than I am (and I'm fully willing to admit that may be the case).
That means there could be another drama with migrations if that would be done.
I think the most likely way they can effectively eliminate GIL would be to provide a compile option that would basically say "this enables paralellization, but your code is bo longer allowed to do A, B, C (there probably would be a lot more things)"
People who want to get it would then adapt their code, and there could be pressure for other packages to make them work in that mode.
While I'm all for increasing single threaded performance[side rant] is this really a good argument? My understanding is that Moore's Law only currently exists because of the existence of more cores. Clock frequency has stagnated since 2004[0]. I mean feature size (Moore's Law) still exists[1] but IPS/core seems significantly flatter than IPS[2]. Aren't most of our performance gains from mutlicore? And as we push more in this direction (e.g. GPU taking over compute) doesn't this make this even worse for python? (Yes I understand that you can make C/CUDA calls but doesn't the GIL make problems here as well as prevent a native python solution?)
[side rant] Still frustrated by things like that difference in speeds between math.sqrt(2.) (~0.002s/10k), np.sqrt(2.) (~0.010/10k), torch.sqrt(torch.tensor([2.])) (~0.039/10k). I know there's more going on in capabilities, but it is of course frustrating by the large differences.
[0] http://cpudb.stanford.edu/visualize/clock_frequency
[1] http://cpudb.stanford.edu/visualize/technology_scaling
[2] https://en.wikipedia.org/wiki/Instructions_per_second#Millio...
Surely it would be possible to drop back to GIL mode if any c extension is loaded which is incompatible with running lockless?
Then you usually get speed, yet still maintain compatibility.
It'd be slightly magical to do. You'd probably have a giant RWLock, which is used for checking whether you're in the "lock free" mode. But at least almost all code could hit it only for read, and it could go away one day.
For your particular usecase, yes. Personally I've been using Python for like 20 years for various tasks and so far never got really bothered by the presence of it once. Worst case was having to wait somewhat longer for things to complete. For my case: still worth it compared to making things multithreaded. And async fixed the rest. And the things which I actually need to be fast aren't usually in Python anyway. I'm not saying the GIL should stay, it's just that it doesn't seem as much of a problem in the general land of Python. Or in other words: how many Python users out there even know what GIL means and does?
The use case they are describing is a standard web server or web application. That's a pretty important and widely applicable use case to dismiss out of hand as "your particular usecase".
Python multiprocessing is pretty usable.
I like multithreading, but also...it has more footguns then the rest of programming combined. [1]
I'm not convinced Python's approach is that bad in practice.
The time it got me was a thread just to timeout another process. Tests worked great but the timeout didn't work in production because the call it was wrapping was calling out to C code so nothing would run until the call returned. We even still got the timeout error in the logs and it looked like it was working (it even tossed the now waited for valid results), but not at the time of the timeout but after the call finally returned a few hours later.
To be fair to Python and the GIL, it's totally capable of parallelizing requests when most of the work is network-bound, which is probably the common case. And when the work is CPU-bound, but the CPU-intensive part is written in C, it's also possible for C to release the GIL. So it's really only "heavy computational work directly in Python" programs that are affected by this. (On the other hand, Python applications do naturally expand to look like this over time...)
I believe the implementation of the Python multiprocessing package uses fork() on *nix systems which means memory should be copy-on-write.
Processes do have the advantage of being self-contained meaning if one crashes, then it will not take down the entire system. Also, the message passing model can theoretically scale to processes running on separate hardware. Thread's cannot do that.
The multiprocessing+asyncio in Python fulfills the aspect of utilizing all the resources, albeit at a higher memory cost, but memory is dirt cheap these days. You have a master process and then worker threads. For all things that you would write in Python, where in >90% cases you are network latency limited, the paradigm of a master process and worker processes with IPC on unix sockets works extremely well. Set up a web app with fast api/gunicorn master/uvicorn workers, and it will be plenty fast enough for anything you do.
If you want to reach peak performance single-threaded app with no locks is the way to go, and work being sharded (not shared) among multiple single-threaded apps.
Multi-threaded apps with shared state introduce more complexity, than the performance when compared to multiple single-threaded apps running asyncio event loop.
For example LMAX Disruptor
I really wish that GIL go away. It is better to pay this price now, multi-threading is the future.
Haha, reminds me of an image I saw with a farmer from some developing country saying "irrigation is the future".
For everyone else multithreading has been the status quo for quite a long time.
However, that leaves a lot of C code that you can't talk to anymore because the C code requires the old Python FFI. I think this is where the main problem lies.
"It's easy to lower the air-conditioning costs of Las Vegas: just move the town to New England".
The problem is "how to remove the GIL" in abstract. It's how to remove the GIL, not impact extensions at all (or as little as possible), keep single threaded performance, and have zero impact to user programs.
To which the above isn't any kind of solution.
Sure, if you don't mind paying a 50-90% performance impact on single threaded performance or completely abandon C-API compatibility and have C extensions start from scratch then there are simple approaches.
If you look at any example in the past to remove the GIL you would see that keeping these two requirements of not having terrible single threaded performance and not having almost a completely new C-API is actually very complex and takes a lot of expertise to implement.
This is exactly the problem, but people have a hard time grasping this because most people interacting with Python have no understanding of how C code interacts with Python, or don't understand the C module ecosystem. I'm not sure if the Python community has a good accounting of this either because I don't recall seeing much quantitative analysis of how many modules would need to be updated etc.
This would help compare with the Python 2 to 3 conversion efforts. Even then, the site listing (shaming?) popular modules with compatibility made a mid-to-late appearance in the process of killing Python 2. Quantification of module updates is obvious thing to have from the get-go for anyone looking to follow through on removing the GIL, but it's not a fun task.
~40 of the programs I am responsible for are single threaded. They were relatively quick to develop and were made by Electrical Engineers rather than career/degreed programmers.
2 programs use multithreading, I had to do that. The learning curve was not a huge deal, but the development time adds at least hours. In my case days(due to testing).
I imagine its too hard to have an optional flag at the start of each program that can let the user decide?
Adding nogil would mean deep changes to the interpreter. I imagine maintaining both versions would be almost like forking the project.
So? some "hours of development time" is nothing.
CPython maintains Python's original purpose as a glue language. You know how much worse CPython would be for that use-case without the GIL.
GVR has said he'll support removing the GIL as long as there's no performance hit. Otherwise, it's simply asking for a fundamental change of direction and too much sacrifice from everyone who needs CPython specifically, just to improve the productivity of people who could use a different Python.
The actual next-step proposal toward no-gil is GIL as a build-time flag (which isn’t quite the same as a runtime flag, but not too far off, either.)
Those that are multi-threaded are seeing minor to medium load.
If expecting extreme load (like Twitter scale), then Python is usually not the answer (rather go to a statically typed language like Java, Go, Rust etc).
obviously if multithreading is near-useless in python, very few programs will take advantage of it.
Yes, they are single threaded, because using multiple threads brings very little benefit in most cases...
> If expecting extreme load (like Twitter scale), then Python is usually not the answer (rather go to a statically typed language like Java, Go, Rust etc).
So that means we shouldn't get any performance improvements, because there are faster languages out there?
Yes, with ML powered compilers recognizing what you are trying to do and generating the actual multithreaded code for you.
And it won't be multithreaded code like you know it, in the sense of os specific threading code with context switching and what not. It will be compiled compute graphs targeted at specific ML hardware, likely with static addressing.
Also, no matter how much you wish it otherwise, retrofitting concurrency on an existing project guarantees that you'll wind up with subtle concurrency bugs. You might not encounter them often, and they're hard to spot, but they'll be there.
Furthermore existing libraries that expect to be single-threaded are now a potential source of concurrency bugs. And there is no particular reason to expect the authors of said libraries to have either the skills or interest to track those bugs down and fix them. Nor do I expect that multi-threaded enthusiasts who use those libraries in unwise ways will recognize the potential problems. Particularly not in a dynamic language like Python that doesn't have great tool support for tracking down such bugs in an automated way.
As a result if "no GIL" ever gets merged, I expect that the whole Python ecosystem will get much worse as well. But that's no skin off of my back - I've learned plenty of languages. I can simply learn one that hasn't (yet) made this category of mistake.
I'm looking for an approach to writing concurrent code with parallelism that is elegant and easy to understand and hard to introduce bugs. This requires alternative programming approaches and in my perspective, alternative notations.
One such design uses monotonic state machines which can only move in one direction. I've designed a syntax and written a parser and very toy runtime for the notation.
https://github.com/samsquire/ideas5#56-stateful-circle-progr...
https://github.com/samsquire/ideas4#558-state-machine-formul...
The idea is inspired by LMAX Disruptor and queuing systems.
That's basically what all machine learning code written in Python does. It calls out to libraries that can themselves parallelize, use the GPU, etc. And then gets the answer back. You get parallelism without any special Python support.
Out of curiosity, have you done any Rust programming and used Rayon?
It's hard to convey how easy and impactful multi-threading can be if properly enclosed in a safe abstraction.
It's hard to convey how difficult it would be to retrofit python to be able to truly "enclose multithreading in a safe abstraction".
See https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.h... for more.
It's 2023 already. 1988 called.
It turns out that when the programmer doesn't understand what the tool says, managers believe the programmer and throw out the tool. Coverity was finding itself in situations where they were finding real bugs, and being punished for it by losing the sale. So they removed the checks for those bugs.
I'll revisit my opinion of multithreaded code when things like that stop happening. In the meantime there are models of how to run code on multiple threads that work well enough with different primitives. See Erlang, Go, and Rust for three of them. Also, if you squint sideways, microservices. (Though most people set up microservices in a way that makes debugging problematic. Topic for another day.)
I think everyone would agree that trying to combine both would be ideal!
"A fast, free threading Python"
https://discuss.python.org/t/a-fast-free-threading-python/27...
Not that I disagree with the recommendation, but one of the sides saying “as long as resources make us choose, choose my side” is...not really surprising.
I think from memory "Faster Python" is Microsoft funded and "No GIL" is funded by Facebook. If they can find a way to fund a combined effort that would be good.
I suspect the conflicting funding also adds to the general political difficulty around this.
I think the fact that you can name two other recent things which have divided the community is a solid argument for being a least a little gunshy about making big, breaking changes. There's the cost of the changes themselves, but there's also a cost to the language as a whole to add yet-another-upheaval.
Performance is important, but not breaking things is also important. I can understand the appeal of doing something suboptimal (but better than current) in favor of not introducing a bunch of harder to predict side effects, both in code and the community.
If so, sub interpreters invite all kinds of nasty bugs. Keep in mind that porting the most popular extensions is an easy exercise so the more interesting question is how this hidden majority of extensions fares.
The serialization thing is also a huge issue. Half of the time I want to use multiprocessing I end up finding that the serialization of data is the bottleneck and have to somehow re-architect my code to minimize it.
I would much prefer a world in which asyncio is 2x faster and can benefit from real parallelism across threads. Libraries like anyio already make it super easy to work with async + threads. It would make Python a viable option for workloads where it currently just isn't.
Have a look at the current documentation for writing extensions. This approach is essentially unchanged since Python 2.0. https://docs.python.org/3/extending/newtypes_tutorial.html
In particular note how everything is declared static - ie only one instance of that data item will exist. If there are multiple interpreters then there needs to be one instance per sub-interpreter. That means no more static and initialisation has to be changed to attach these to the module object which is then attached to a specific interpreter instance. It also means every location you needed to access a previously static item (which often happens) has to change from a direct reference through new APIs chasing back from objects to get their owning module and then get the reference. That is the code churn the PyO3 issue is having to address. One bonus however is that you can then cleanly unload modules.
This may still not be sufficient. For example I wrap SQLite and it has some global items like a logging callback. If my module was loaded into two different sub interpreters and both registered the logging callback, only one would win. These kind of gnarly issues are hard to discover and diagnose.
Removing the GIL also won't magically help. I already release it at every possible opportunity. If it did go away, I would have to reintroduce a lock anyway to prevent concurrency in certain places. And there would have to be more locking around various Python data structures. For example if I am processing items in a list, I'd need a lock to prevent the list changing while processing. Currently the GIL handles that and ensures fewer bugs.
I've also experienced the serialization overhead with multiprocessing. I made a client's code so much faster that any form of Python concurrency was slower because of all the overhead. I had to rearchitect the code to work on batches of data items instead of the far more natural one at a time. That finally allowed a performance improvement with multiprocessing.
I was listening to the interview with Chris Lattner with Lex Friedman a week ago or so. Very interesting discussion on his project mojo which intends to build a new language that is backwards compatible and a drop in replacement for python with opt in strict typing, better support for native/primitive types where this makes sense, easier integrations with hardware optimizations, and of course no GIL. The idea would be that the migration path for existing code is that it should just work and then you optimize it and provide the compiler with type hints and other information so it can do a better job. Very ambitious roadmap and I'm curious to see if they'll be able to deliver.
The main goal seems to be to enable programmers to do the things you currently can't do in python because it's too slow in python without running into a brick wall in terms of performance.
I mostly work with JVM languages and a few other things but I occasionally do a bit with python as well. I've always liked it as a language but I'm by no means an expert in it. I recently spent a day building a simple geocoder and since I know about the GIL, I went straight for the multi processing library and did not bother with threads. IMHO there's absolutely no point in attempting to use threads with python with the GIL in place. I needed to geocode a few hundred thousand things in a reasonable time frame, so all I wanted to do was use a few different processes concurrently so I could cut down the runtime to something reasonable.
Python is ok for single threaded stuff but you run into a brickwall doing anything with multiple processes or threads and juggling state. In the end I just gave up and wrote a bunch of logic that splits the input into files, processes the files with separate processes, waits for that to finish, and then combines the output files. Just a lot of silly boiler plate and abusing the file system for sharing state. It does what it needs to but it feels a bit primitive and backwards and I'm not proud of the solution.
Removing the GIL, adding some structured concurrency, and maybe some other features, would make python a lot more capable for data processing. And since there are a lot of people already use python for that sort of thing, I don't think that would be such a bad thing. Data science and data processing are the core use case for python. I don't think people actually care a lot about the raw python performance. It's never been that great to begin with. If it's performance critical, it's mostly being done via native libraries already.
indeed. one would almost hope that all the different aspects of "performance" and "concurency", their memory, disk or network profile etc get their own dedicated labels. The conflation of these distinct dimensions is a major source of confusion (and thus a waste of bandwidth).
[0] https://docs.python.org/3/library/asyncio-task.html#asyncio....
[1] https://docs.python.org/3/library/asyncio-task.html#asyncio....
If you’ve broken up the input already I’d use the shell to parallelize, ie for &. If network, async is probably what you want.
Python has blocking IO. So a network call blocks the process. So if you have 250ms response times, you are doing 4 requests per second. Without the GIL, threads would be a good way to scale that. With 10 threads you should be able to do 2400 requests per minute. But with the GIL forget about that. With co-routines and non blocking IO, it could all be single threaded. There are some ways to do that with python of course but then you are going to have to use some specialized frameworks and step away from the standard library a bit.
Using the shell vs. the multi processing module is the same difference. I've done both with python. I've a slight preference for the multi processing module so I don't have to deal with bash weirdness on top of all the python boiler plate. The first time I did stuff like that with python was probably 13 years ago or so around 2010. Not a lot has changed or progressed on this front since then in python. The GIL made scaling this unnecessarily hard then and it still does. Threads are a no go because of it, the standard library mostly offers blocking IO, and when you go with multiprocessing things like shared memory are very limited so you end up using files or databases for state.
Things like node.js, go, or kotlin would handle this type of work load with a lot less fuss. With Kotlin, I'd be using co-routines and some multi threaded scope to launch them in. Or I could build on some of the Java internals. Or a mix of both. I'd be able to write similar code and choose between blocking or non blocking IO. I'd be forking and joining things. Maybe use channels and flows to pass data around and rely on back pressure to keep things progressing at a more or less optimal rate. Not an option for this project as my client just is more python focused and that's fine. But just signaling that python is a bit out of its depth here. Just singling out kotlin here because I just have spend a lot of time with it. If you have a hammer everything seems a nail.
I think python could be so much better but that starts with modernizing its internals. Mojo seems like a huge step in the right direction.
10% doesn't look too much to me, I still don't get why today people care so much about single thread performance.
If no-GIL has a 10% single thread performance hit, that means that essentially all my existing python code would be that much worse.
Maybe in a 100% CPU bound code, most of the code is I/O bound and no one will notice the change, just my opinion.
So? Especially since the "Faster Python" team already made Python 1.11 "10–60% Faster than 3.10", and 1.12 is even faster still, whereas their overall plan is to get it to 2-5 times faster compared to 3.9.
So at the worst case, with a 10% hit, you'd balance out the 3.11 speed, and your code would be as fast as 3.10.
Why havent you implemented multithreading?
(don't get me wrong, I know the cost of implementation, but if speed matters, multithreading is a very reasonable step in python)
The impact won't be on users / Python programmers who don't develop native extensions. It will suck for people who had a painful workaround for Pythons crappy parallelism already, but now will have to have two workarounds for different kinds of brokenness. It still pays off to make these native extensions, however their authors will create a lot of problems for the clueless majority of Python users, which will like end up in some magical "workarounds" for problems introduced by this change very few people understand. This will result in more cargo cult in the community that's already on the witch hunt.
For about 10 minutes a few years ago, when the M1 had the best single threaded performance per buck, people cared.
Now that the M1 isnt the leader in single threaded, we are back to the 'multithread is most important'.
Which has always been true. If your program needs an improvement in speed, you can multithread it. The opposite isnt true.
What do you mean by "the opposite"? "If your program doesn't need an improvement in speed, you can't multithread it"? "If you can multithread your program, then it doesn't need an improvement in speed"? Well, yeah, obviously both of those statements are false but they're also quite useless, so who cares?
This is smart, though, because (even if it's not great) there's a lot of evidence that it works in practice. Specifically, this is almost exactly what JavaScript does with workers. It's not a great API and it's cumbersome to write code for, but it got implemented successfully and people use it successfully (and it didn't slow down the whole web).
Removing the GIL seems like it could make things more complicated in many ways by making lots of currently thread-safe code subtly unsafe, but I might be wrong about this. (...in which case it would just make things very slow because everything is synchronized?)
It is a NIH syndrome, if a big project doesn't originate in the dev team, it will not be accepted.
If its garbage collection that's the problem, I think you could transfer ownership between threads, so the subinterpreter takes ownership of the object and all references to it in the source interpreter are voided.
Alternatively you can do something like Java and all objects are in a global object allocator, passing things between threads doesn't require interpretation, just a reference.
I suspect there will be some butting of heads for a while before they work things out after seeing how the community reacts. All of this could be handled better with some thoughtful proactive engagement, but that's not really how things operate and there is no one to really enforce it.
The price is an added complexity of the code base.
I truly don't understand why Python always gets a pass and people applaud every announcement, no matter how trivial or elusive it is.
The GIL effort is another matter. I'd rather have a simple interpreter with no-GIL than this mess of relatively small speedups.
But like other GvR efforts where he presided over a small group of people who did the work his efforts will of course go in. Like asyncio, the suboptimal "match" statement, the peg parser (which adds new workloads for other implementations because the de-facto DFL cannot be bothered with publishing an LALR grammar).
Python is a glue language, people can go elsewhere for speed.
Much as No GIL would be an adventure, I'm leaning towards the more gradual and stable changes from the FasterPython team and I can see that throwing No GIL into the mix adds complexity at an inopportune moment.
https://discuss.python.org/t/a-fast-free-threading-python/27...
I don't develop anything in Python, but it is used by several applications of importance to me. The lack of compatibility between versions is a thing that bites me hard, and I tend to curse Python because of it.
I think the arguments are a red herring. It's more rationalizations for not wanting to do it.
For that matter, pip can't even search for packages any more, and instead directs you to browse the pypi website in a browser. Whatever the technical reasons for that, its a user interface fail. Conda can do it!!!!! (as well as just about any package management system I've ever used)
Package management is standardized in a series of PEPs[1]. Some of those PEPs are living documents that have versions maintained under the PyPA packaging specifications[2].
The Python Packaging User Guide[3] is, for most things, the canonical reference for how to do package distribution in Python. It's also maintained by the PyPA.
(I happen to agree, even with all of this, that Python packaging is a bit of a mess. But it's a much better defined mess than it was even 5 years ago, and initiatives to bring packaging into the core need to address ~20 years of packaging debt.)
[1]: https://peps.python.org/topic/packaging/
[2]: https://packaging.python.org/en/latest/specifications/index....
* If you mean a thing that's ultimately meant to be `pip` installable, then you should use `pyproject.toml` with PEP 518 standard metadata. That includes the dependencies for your project; the PyPUG linked above should have an example of that.
* If you mean a thing that's meant to be deployed with a bunch of Python dependencies, then `requirements.txt` is probably still your best bet.
Python isn't perfect, and mostly unsuitable for any system where performance is in consideration.
That leaves everything else including personal utility scripts and packages I use each day to automate random stuff. And I hugely appreciate how fast and simple it is to develop in python, unlike certain languages that literally depends on IDEs due to the verbosity and unnecessary cognitive load.
Indeed it’s crazy. A few pip installs and I had a multiprocessing pandas (dask) with a web gui, and a workflow system (also with a web gui), and a pipeline to convert csv to parquet in like 20 lines of code
But on the other hand I don't really like Go, so maybe it's different languages for different tastes.
However, the sense I got was that it was going to be a lot of work to “fix Python packaging” which wasn't feasible with an all-volunteer group.
At work, we're migrating away from pip as a distribution mechanism for this reason; I don't expect to see meaningful improvements to the developer experience anytime soon.
This is especially true because pip today is roughly where npm was in 2015, so there's a lot of fundamental infrastructure work (including security) that still needs to happen. An example of this is that PyPI just got the ability to namespace packages.
You're thinking of organizations, which are not namespaces: https://blog.pypi.org/posts/2023-04-23-introducing-pypi-orga...
LWN even used namespaces in the title of the article describing the feature, which doesn’t help the confusion: https://lwn.net/Articles/930509/
Could you elaborate on what you’re using as a replacement?
- clear separation of dev and production dependencies - lock file with the current version of all dependencies for reproducible builds (this is slightly difference than the dependency specification) - no accidental global installs because you forgot to activate a virtual environment - (not sure if supported by pip) allows installing libraries directly from a git repo, which is very useful if you have internal libraries - easier updates
1. curl script that installs dbt for end users
2. zipped snapshots for dbt Cloud, the SaaS hosted version of dbt
Eventually we want to create Docker images from 2, but we’re not there yet.
Person with limited to zero experience with CPython internals> I hate the GIL, why don't they just remove it?
That just is doing an incredible amount of heavy lifting. It'd be like saying, "Why doesn't the USA just switch entirely to the metric system?" It's a huge ask, and after being burned by the 2/3 transition, the python team is loathe to rock to boat too much again.
The GIL is deep, arguably one of the deepest abstractions in the codebase, up there with PyObject itself. Think about having to redefine the String implementation of a codebase in your language of choice.
Whatever your monday-morning quarterback idea on how to pull out the GIL is, I can almost guarantee, someone has thought about it, probably implemented it, and determined it will have one or more side effects:
- Reduced single-thread performance
- Breaking ABI/FFI compatibility
- Not breaking ABI immediately, but massively introducing the risk of hard to track concurrency bugs that didn't exist before, because GIL
- Creating a maintenance nightmare by adding tons of complexity, switches, conditionals, etc to the codebase
The team has already decided those tradeoffs are not really justifiable.
The GILectomy project has probably come the closest, but it impacts single-thread performance by introducing a mutex (there are some reference type tricks [1] to mitigate the hit, but it still hurts run time 10-50%), and necessitates any extension libraries update their code in a strongly API-breaking way.
It's possible that over time, there are improvements which simultaneously improve performance or maintainability, while also lessening the pain of a future GILectomy, e.g. anything which reduces the reliance on checking reference counts.
[1] PEP 683 is probably a prerequisite for any future GILectomy attempts, which looks like it has been accepted, which is great https://peps.python.org/pep-0683/
Unavoidable performance costs and reduced safety equals massive friction no matter how it's approached. It's not a question of "are we smart enough to make this better in every way", since the answer is "no, and nobody can be, because it can't be done". It's only "will we make this divisive change".
The cost of switching increases over time and will increase further and further, making it less and less likely. Would have been way cheaper back then.
The US started that in either 1875 or 1893, though, and somewhat more aggressively in 1975.
It reversed course in the 1980s, it didn't fail to start before that.
Today Python is one of the world's most popular programming language, if not the most popular language. The GIL is limiting and a trade-off in itself of course – designing any programming language is an exercise in trade-offs. But clearly Python has gotten quite far with the set of trade-offs it has chosen: you need to be careful to "just" radically change the set of trade-offs that have proven themselves to be quite successful.
> The GIL is deep, arguably one of the deepest abstractions in the codebase, up there with PyObject itself. Think about having to redefine the String implementation of a codebase in your language of choice.
I am somewhat familiar with the cpython code base, and talk to some folks involves in some of thousand new python runtime.
The problem is not that deep, and cpython is not that much different from other projects : the GIL is an implementation details that leaked through the API and now we have a bunch of people are relying on it. The question is what do we do about it. The trade-off in such situation are well known and just a question to pick the right one.
> The team has already decided those tradeoffs are not really justifiable.
That's from my view the crust of the issue, the TLDR is that GIL-less python is not a priority for the python team, so they view any trade-off/comprise as "not justifiable". Especially something when it come to added complexity to the code base or what not...
> Person with limited to zero experience with CPython internals> I hate the GIL, why don't they just remove it?
People have this reaction because having a single-threaded interpreter in 2023 is just ... embarrassing, what ever the reasons behind it.
You can disagree without assuming that i am not familiar with the subject.
The link you provided is from 2007 so i am not sure how fair it is to quote guido from then. But i am not sure the link demonstrate the point you are trying to make, from guido himself :
> While it is my personal opinion, based upon the above considerations, that there isn't enough value in removing the GIL to warrant the effort.
Edit : If you want a newer reference, this HN threads and the links discribe the situation well https://news.ycombinator.com/item?id=36240998
Which is the point i am making... This is not really a technical issue, the python just doesn't think it's worth the effort.
Technically yes, the data structure can be abstracted over and removed, in that sense, it isn't "deep". But the reason I say it's deep is because of the deep implications and assumptions of the GIL being there. For decades, the codebase (and extensions) has grown with the expectation that the GIL enforces a certain behavior.
> That's from my view the crust of the issue, the TLDR is that GIL-less python is not a priority for the python team, so they view any trade-off/comprise as "not justifiable". Especially something when it come to added complexity to the code base or what not...
Precisely. Because it's such a hard problem. If someone had a proposal to actually remove the GIL, limit the single core performance hit to say <10%, and not break extensions, I have no doubt the steering team would go for it. It would be huge PR for python, simply because of the Gil's bad rap.
Turns out that multi-interpreters give you most of the benefit of multithreading with nowhere near as much complexity.
> People have this reaction because having a single-threaded interpreter in 2023 is just ... embarrassing, what ever the reasons behind it.
What other dynamic languages invented over 3 decade ago have natively multithreaded interpreters? Oh javascript, the (fundamentally simpler on a technical level and uses different gc techniques) language which has gotten millions of dollars in development by the biggest tech companies because it runs on nearly every browser and thus has huge incentives to optimize? If python ran in every browser, the Gil would be gone by now.
Java? Again, huge amount of backing, 15 years older than python.
Perl, ruby, lua, all use refcount and have single-threaded interpreters. Objective C might fit the bill for multithreaded refcount gc (I don't know, I'm asking gpt). Nim does, but it's rather modern, (2008). Swift is statically typed, which helps, and much newer (2014).
I guess that leaves Erlang, which again uses different gc techniques.
I guess the takeaway is refcount is probably not the best design choice for writing a modern dynamic language if you value multithreading.
As i mentioned... The idea of keeping backward compact. of an implementation details which leaked into the API is kinda common. Some of the current proposal are about making the gil optional, keeping the compact for those cases...
> Precisely. Because it's such a hard problem. If someone had a proposal to actually remove the GIL, limit the single core performance hit to say <10%, and not break extensions, I have no doubt the steering team would go for it. It would be huge PR for python, simply because of the Gil's bad rap.
I think this might be were we disagree the most. One doesn't sit around, put a collection of constraints into the ether and expect a solution to magically appear... Obviously every one wants a perfect solution to technical problems, but those don't really exists.
The true measure of the willingness of the council to accept gil is about the compromises they are willing to make to accept external solutions or the effort put into developing their own solutions.
Even if the council just had put some effort into developing a suits of test cases (both performance and correctness), or try to pull some statistical information on how many C extensions rely on the gil for correct behavior, how hard would a transition for those be? can we leverage runtime tooling like valgrind and/or llvm (thread|memory)sanitizer to detect some and ease the transition.
But i haven't seen any real effort, just the same list of constraints we had the last 10 years.
> Turns out that multi-interpreters give you most of the benefit of multithreading with nowhere near as much complexity.
I am only tangentially familiar with the sub interpreter proposal, but what i understand, i disagree. This the classic sharing memory vs message passing trade-off...
Also not to forget that this does might still break C-extension which sometime relies on static variable (like the comment from the author or mysql extension mentioned).
But i don't want to make this about this or that specific proposal. if the council prefer sub interpreter approach to nogil, they should say so and don't have people waste their time.
> What other dynamic languages invented over 3 decade ago have natively multithreaded interpreters? Oh javascript, the (fundamentally simpler on a technical level and uses different gc techniques) language which has gotten millions of dollars in development by the biggest tech companies because it runs on nearly every browser and thus has huge incentives to optimize? If python ran in every browser, the Gil would be gone by now. > Java? Again, huge amount of backing, 15 years older than python. > Perl, ruby, lua, all use refcount and have single-threaded interpreters. Objective C might fit the bill for multithreaded refcount gc (I don't know, I'm asking gpt). Nim does, but it's rather modern, (2008). Swift is statically typed, which helps, and much newer (2014).
I don't want to sound to harsh, but you go to war with the army you have, not the army you want. The question is not what the optimal solution would look like if we had optimal conditions (deeper pockets, gc vs refc, etc... etc...). Python is what python is, the python organization have the resources that they have. No doubt we could design a better solution with more money or a with a language with better semantic, but don't have neither and that shouldn't prevent the council of acting on the best solution we have right now...
Our ultimate goal is to integrate a JIT into CPythonThe nogil effort seems like such a better solution, that even if it breaks the C interface, subinterpreters aren't worth considering.
I will give it a shot.
Subinterpreters are better than multiple processes because:
- they have significantly less memory overhead
- they can move objects much faster between subinterpreters because they don’t need to serialize through a format like JSON
- since they are all in the same process you can implement things like atomics or channels easily.
Subinterpreter are better then no-Gil because:
- they make the code easier to reason about and debug relative to raw multi-theading
- they don’t negatively impact single threaded (basically all existing) python code performance
- they don’t require any changes to the C interface, preventing a fractured ecosystem
- they can’t have data races
Why do you think that you would need to serialize to JSON? Pipes and sockets can deal with binary data just fine. With shared memory, there wouldn't be any difference at all.
> - since they are all in the same process you can implement things like atomics or channels easily.
This is also possible with shared memory.
AFAICT the advantage of subinterpreters over subprocesses are:
- lower memory overhead
- faster creation/destruction time
- ability to share global data (with subprocesses the data would either need to be duplicated or live in shared memory)
But you do bring up some good points for ways you could achieve similar goals without the need to make the interpreters thread safe.
That would be a huge advantage, but it's not there yet. According to PEP 554 [1] the only mechanism for sharing data is sending bytes through OS pipes, which is exactly the same as for multiprocessing and requires the same sort of serialization.
https://docs.python.org/3/library/multiprocessing.html#multi...
In a message passing system there’s always going to need to be some form of serialization. I’ll wager that pickle is fast and flexible enough for most cases and for those that aren’t, using something like flatbuffers or capn proto in shared memory wouldn’t be too much of a lift to integrate.
Although all of that has long been possible in a multiple-process architecture, so I’m also curious to know if there are any real advantages to subinterpreters. From this message [1] linked to from the PEP it sounds like the author once thought that object sharing was a possibility, but if it’s not there seem to be no real benefits over multiprocessing and one big downside (the GIL).
Contrast with ruby’s Ractor system [2], which is similar to the subinterpreter concept but allows true parallelism within a single process by giving each ractor its own interpreter lock, along with a system for marking an object as immutable so it can be shared among ractors.
[1] https://mail.python.org/pipermail/python-ideas/2017-Septembe...
I think this deserves an extra callout because even your multi-threaded Python programs are effectively single threaded and benefiting from the performance gain.
- They absolutely do have to serialize, usually via pickle. I'm pretty sure objects are not sharable between subinterpreters and there is not a plan for that. The main reason people think subinterpreters are good ("you can just share the memory!") is not actually true.
- They don't require any changes to the C interface because those changes were already made, and a fair amount of cost was paid by C library maintainers. So it's true, subinterpreters are at an advantage in this regard, but that's more of a political question than a technical one
How so? Asking out of curiosity.
Which isn't really different than a similar pattern of isolation in threading or multiprocessing.
The hidden really hard problem is that extension modules may have been written relying on GIL behavior for thread safety... these may be undocumented and unmaintained.
Even so I hope the community decides it is worth it. A glue language with actual MT support would be much more useful.
> Even if it breaks the c interface
Than most of your python packages wouldn't work. A python that isn't backwards compatible? Ya, that has been tried once before, and was a disaster. If you want a non-backwards compatible gil-less python, it already exists. You can find versions of nogil online.
I suspect sub-interpreters are a punt and a feint.
My guess is that there will likely be exactly 2 sub-interpreters in most Python code. One which talks to an old C API with a GIL and one which talks to a new C API without a GIL.
It's going to be a lot easier to manage handing objects between two Python sub-interpreters than to manage handing objects between two incompatible ABIs.
> C++ and Java developers expect to be able to run a program at full speed (or very close to it) under a debugger.
I haven't worked in Java too much, but in C++ I don't remember having this expectation
However I'd be glad if profilers (and notably memory profiler) would slow down a Python program only as much as valgrind does C.
IMHO the Python community has intentionally torpedoed all competing implementations of Python besides CPython to its own detriment. They seem to constantly make the task of making a compatible VM harder and harder, on purpose. The task they face now is basically building a new, sophisticated VM inside a very much non-sophisticated VM with a ton of legacy baggage. A massive task.
>> In this case, multiple interpreter support provide a novel concurrency model focused on isolated threads of execution. Furthermore, they provide an opportunity for changes in CPython that will allow simultaneous use of multiple CPU cores (currently prevented by the GIL–see PEP 684).
This whole thing seems more like something developer wants to do (hey, it's novel!) than something users want. To the extent they do want it, removing the GIL is probably preferable IMHO. That a global lock is a sacred cow in 2023 seems strange to me.
Maybe I'm misunderstanding, but I don't want an API to manage interpreters any more than I want one for managing my CPU cores. Just get me unhindered threads ;-)
I use Python threads for some IO heavy work with Popen and C and Java for my true multithreading work.
Personally I'd like to see Python continue as the amazing multitool that it is has always been.
Go is the natural concurrency sibling for Python. High performance parts of Python applications should be linked to Go binaries, or simply be written entirely in Go.
Ideally Go linkage would be highly integrated into Python. There is a huge place in the world for GIL constrained Python. Enabling Python to push further into high performance environments is just going to make a problem worse.
This is a worthwhile watch on this topic: https://youtu.be/cMMAGIefZuM
I wonder if the plan written there is current.
It sounds like you may want to feel like you have a complete understanding of classes, objects, and the way the work before you can begin working with them. This can almost never work. I haven't come across a topic where just reading about the topic is sufficient to fully understand it or even become proficient in it.
In my experience this is true for cooking, lab techniques in chemistry, electronics, and programming. Even when I have read something and felt that I understood it completely, as soon as I begin the activity I immediately realize that I had a fundamental misunderstanding of what I had read. That my brain had made some oversimplification or skipped passed some details so that I felt like I grasped the concept.
So if I had to describe the way I learn a new concept it would look like this:
1. Read many different descriptions/watch many different videos of the topic to get used to the terms and concepts
2. Try to apply those concepts in real life (write software, build a circuit, cook a meal)
3. Figure out where my understanding fell short, and go back to step 1
You want to make this loop as tight as possible. When you become expert at something you can do this activity super fast. When you first start out you may have to do quite a bit of reading to even have the baseline needed to attempt a concrete task. However, it is important to get started towards a real goal as soon as possible or you will be wasting your time feeling like you are learning and moving towards you goal, but you are not.
Classes and blueprints have a simple analogy that I'm sure you are familiar with.
Blueprints are instructions for how to build something, like a house. Once built, the house is a physical thing you can interact with. It has attributes, such as a height or color. It has things it can do or that can be done to it, like open a door or turn on some lights.
Classes are blueprints - they tell a computer how to build something. An object is what is built by the class - it has attributes and methods.
https://death.andgravity.com/same-arguments
And it doesn't fall into the "Dog inherits from Animal" taxonomic crap.
Programming is not a "school" activity for me. It's a craft, you do stuff. That has eventually led to a depth of knowledge in various topics inside programming.
(Digression: With that said - we should think of a lot more "school" stuff as skills and crafts - stuff that you don't read to understand but you get better at with practice. A lot of maths class is skills, not knowledge.)
Learn by doing, don't learn by studying.
Pick a (hopefully real) problem, solve it using classes. Repeat. Continue repeating. You will either learn what OO is good for, what it is not good for and how you can use it to write better code. Or, learn that programming is not something you can grok.
If you don't have a "real" problem; Then write program to play tic-tac-toe; manage the and display board, take player inputs, detect when game is done (winner or draw).
Then expand it to 8x8 board, then to 3 players. Those changes should be easy with good OO design (lots rewrites, code changes). And probably "harder" with bad OO or no OO design.
btw this is 2nd interview question I and my team used for years.
But I would maybe recommend a good book if you're struggling.
What you just proposed is exactly what isn’t working for this person.
- Python started as a simple language, but it's grown over the decades, and professional programmers learned the new complications along the way. They don't naturally appreciate what it's like if you get hit with them all together, as sometimes happens -- it all seems simple to them. So to understand OO I would try to screen out the fancier bits like the class variables you mentioned -- you can come back to them later.
- The original central idea of objects (from Smalltalk) is, an object is a thing that can receive different commands ('methods' in Python), and update its own variables and call on other objects. The way Python gives you to define objects (by defining a class and then creating an instance of the class) is not the most direct possible way it could've been designed to do this -- if it feels more complicated than necessary, it kind of is. But it's not too bad, you can get used to how it works for the most central stuff as I mentioned, and learn more from there.
Finally, 15 years later Python might also get something similar to VisualVM.
But any C extensions that rely on the GIL for thread safety would be an issue..
FWIW, parallel implementations already exist, and maybe RustPython can join them.
- The GIL is a feature that adds value, and was added for a reason. (As explained elsewhere in discussion)
And, if we want to be a bit less charitable about it;
- The GIL is a feature, in much the same way training-wheels on your bike is a feature. :-)
I think it's very magnanimous of the python team, by not removing the GIL, to give Go, Java and C++ a chance.