58 ms·
Python has had async for 10 years – why isn't it more popular?
- fullstop 1y agoExceptions are difficult to deal with. Also, while they've had async for 10 years it has changed quite a bit from the initial incarnation.
- blibble 1y agothere are some Exception situations that are almost completely impossible to deal with like guaranteeing a close() inside a finally asyncio is a terrible, terrible library
- kamikaz1k 1y agoasync python is awful. to me it is a by default avoid. and when you can't avoid, use only where it provides outsized benefit.
- TZubiri 1y agoSometimes less is more. When a program becomes so big, one of the hardest challenges is not to keep on adding stuff.
- PaulHoule 1y agoI went through a phase of writing asyncio servers for my side projects. Probably the most fun I had was writing things that were responsive in complex ways, such as a websockets server that was also listening on message queues or on a TCP connection to a Denon HEOS music player. Eventually I wrote an "image sorter" that I found was hanging up when the browser was trying to download images in parallel, the image serving should not have been CPU bound, I was even using sendfile(), but I think other requests would hold up the CPU and would be block the tiny amount of CPU needed to set up that sendfile. So I switched from aiohttp to the flask API and serve with either Flask or Gunicorn, I even front it with Microsoft IIS or nginx to handle the images so Python doesn't have to. It is a minor hassle because I develop on Windows so I have to run Gunicorn inside WSL2 but it works great and I don't have to think about server performance anymore.
- tdumitrescu 1y agoThat's the main problem with evented servers in general isn't it? If any one of your workloads is cpu-intensive, it has the potential to block the serving of everything else on the same thread, so requests that should always be snappy can end up taking randomly long times in practice. Basically if you have any cpu-heavy work, it shouldn't go in that same server.
- acdha 1y agoIndeed. async is one of those things which makes a big difference in a handful of scenarios but which got promoted as a best-practice for everything. Python developers have simply joined Node and Go developers in learning that it’s not magic “go faster” spray and reasoning about things like peak memory load or shared resource management can be harder.
- nly 1y agoOS threads are for CPU bound work. Async is for juggling lots of little initialisations, completions, and coordinating work. Many apps are best single threaded with a thread pool to run (single threaded) long running tasks.
- PaulHoule 1y agoMy system is written in Python because it is supported by a number of batch jobs that use code from SBERT, scikit-learn, numpy and such. Currently the server doesn't do any complex calculations but under asyncio it was a strict no-no. Mostly it does database queries and formats HTML responses but it seems like that is still too much CPU. My take on gunicorn is that it doesn't need any tuning or care to handle anything up to the large workgroup size other than maybe "buy some more RAM" -- and now if I want to do some inference in the server or use pandas to generate a report I can do it. If I had to go bigger I probably wouldn't be using Python in the server and would have to face up to either dual language or doing the ML work in a different way. I'm a little intimidated about being on the public web in 2025 though with all the bad webcrawlers. Young 'uns just never learned everything that webcrawler authors knew in 1999. In 2010 there were just two bad Chinese webcrawlers that never sent a lick of traffic to anglophone sites, but now there are new bad webcrawlers every day it seems.
- giancarlostoro 1y agoI think part of it is historical. WSGI has been around a while before async became relevant. The industry now has had ASGI for a while, but if your WSGI deployed web application doesn't need to squeeze out all the juice it can with async, you might not be phased by not using it or bothered at all. Reminds me of how long it took some to go from Python 2 to Python 3.
- baq 1y agoasync, parallelism, concurrency, why not all three? JS, the canonical async (at least today) language, has had neither parallelism nor concurrency primitives for a good decade or so after its inception. I personally blame low async adoption in Python on 1) general reduction in its popularity vs Typescript+node, which is driven by the desire to have a single stack on the frontend and backend, not by bad or good async implementations in Python (see also: Rails, once the poster child of the Web, now nearly forgotten) 2) lack of good async stdlib. parallelism and concurrency are distant thirds.
- dragonwriter 1y ago> async, parallelism, concurrency, why not all three? async is a concurrency mechanism.
- JackSlateur 1y agoasync enables a concurrency potential, nothing more That is, if you use external stuff and can delegate work to them, then async is concurrent (async io for instance) But if you do not, then async is regular code with extra steps
- DanielHB 1y agoI do not understand what you mean, parallelism is running multiple concurrent execution blocks running in multiple physical CPUs at the same time. My understanding is that JS can't do that (besides service workers which are non-shared memory), but it still has multiple concurrent code-blocks being executed at the same time, just in linear fashion. It will just never use multiple CPU cores at the same time (unless calling some non-JS non-shared-memory code)
- dapperdrake 1y agoPython's async is very difficult to use and debug. It seems to get stuck randomly, read like race conditions. And Python cannot work around this nicely with their lambdas only permitting a single expression in their body. Not worth the trouble. Shell pipelines are way easier to use. Or simply waiting —no pun intended— for the synchronous to finish.
- mixmastamyk 1y ago> lambdas only permitting a single expression Use a tuple, maybe walrus, and return the last item[-1].
- dapperdrake 1y agoThat idea sounds good. How do I get variables for not redoing long-running computations that depend on one-another? So, what if the third tuple value depends on the second and the second in turn depends on the first?
- int_19h 1y agoYou can abuse list and sequence comprehensions for this. `for..in` is effectively a variable binding since you can target a freshly created list or a tuple if you need to bind a single value. So: [x for x in [some_complicated_expression] if x > 0 for y in [x + 1] ... ][0] That said, I wouldn't recommend this because of poor readability.
- mixmastamyk 1y agoThat’s what walrus is for: future = lambda age: ( print('Your age is:', age), older := age + 5, print('Your age in the future:', older), older, )[-1] print(future(20)) # out Your age is: 20 Your age in the future: 25 25
- MichaelRazum 1y agoYou can’t just plug and play it. As soon as you introduce async you need to have the runtime loop and so on. Basically the whole architecture needs to be redesigned
- whilenot-dev 1y agoasyncio has been designed to be as "plug and play" as it gets. I'd discourage it, but one could create async loops wherever one would need them, one separate thread per loop, and adapt the code base in a more granular fashion. Blocking through the GIL will persist, though. For any new app that is mostly IO constraint I'd still encourage the use of asyncio from the beginning.
- odyssey7 1y agoI remember back when the “Pythonic” philosophy was to make the language accessible. It’s clear that Dr. Frankenstein has been at large and managed to get his hands on Python’s corpse.
- kstrauser 1y agoI don’t think that’s fair. Yeah, there is a lot to learn and keep track of. At the same time, it’s an inherently complex problem. From one POV, and async Python program looks a lot like a cooperative multitasking operating system, but with functions instead of processes. It was a lot harder to write well-behaved programs on classic Mac OS than it was on a Commodore 64, but that Mac app was doing an awful lot more than the C64 program was. You couldn’t write them the same way and expect good results, but instead had to go about it a totally different way. It didn’t mean the Mac way was bad, just that it had a lot more inherent complexity.
- MichaelRazum 1y agoSure agree, for bi directional websocket communication it is the way to go. It's just that you have to really think it thorough when using it. Like using asyncio.sleep instead of sleep for example and there are more little things that could easily hurt the performance and advantages of it.
- tripletpeaks 1y agoIt’s probably related to the fact that when they added “await” to JavaScript, it seemed to become the most popular keyword in the language overnight, just comical amounts of it in the average new JavaScript file in the wild.
- lelanthran 1y agoQuite a lot of my js functions don't await; instead I simply return the promise and let the caller `await` or more often attach a `then` as they see fit. The default linter in Vs Code keeps marking those functions with warnings though. Says I should mark them as async
- zelphirkalt 1y agoSomehow I prefer the explicitness of Promise.then().catch(). When I have to do JS. Am I the only one?
- taude 1y agoUse an appropriate language and runtime for the right tool/workload. There's better languages and runtimes to use that have better native concurrency built in.
- tschellenbach 1y agoYes, this!. Its a mess, some typing, some async. No standardization/ one way to do things. Literally goes against the original ZEN of python "There should be one-- and preferably only one --obvious way to do it : Aim for a single, clear solution to a problem. "
- aquariusDue 1y agoCue the zen of python apologists explaining how we just don't get it and that with enough reframing it'll click. Snide remark aside, I actually like the Zen of Python as programming language folklore but in 2025 AD it's kinda crazy to pretend that Python actually adheres to those tenets or whatever you wish to call them, and I'd go as far as to claim that it does a disservice to a language flexible enough for a lot of use cases. There's even someone on YouTube developing a VR game with Python.
- deleted 1y ago[deleted]
- int_19h 1y agoIt has never been literally true anyway, not even back when it was originally written.
- lysace 1y agoBecause it takes a a lot of reading/studying/experimentation to get things right. I'm personally halfway through that journey (having spent like 4h reading docs/learning, on top of the development). I suspect it could have been designed in such a way so that it's less trivially easy to mess up.
- adfm 1y agoTwisted?
- lstodd 1y agoAnd Tornado. Please don't remind me of those horrors.
- atomicnumber3 1y agoThe author gets close to what I think the root problem is, but doesn't call it out. The truth is that in python, async was too little, too late. By the time it was introduced, most people who actually needed to do lots of io concurrently had their own workarounds (forking, etc) and people who didn't actually need it had found out how to get by without it (multiprocessing etc). Meanwhile, go showed us what good green threads can look like. Then java did it too. Meanwhile, js had better async support the whole time. But all it did was show us that async code just plain sucks compared to green thread code that can just block, instead of having to do the async dances. So, why engage with it when you already had good solutions?
- neuroelectron 1y agoEven in Java, async is rarely the right solution. I'm sure in situations where it's needed, Python's async would be used. For instance, it would be good for reducing resource usage in any kind of small service that dynamically scales. The workarounds are much more expensive but that doesn't matter unless you're already resource constrained. Even then, nginx might be a netter solution.
- throw-qqqqq 1y ago> But all it did was show us that async code just plain sucks compared to green thread code that can just block, instead of having to do the async dances. I take so much flak for this opinion at work, but I agree with you 100%. Code that looks synchronous, but is really async, has funny failure modes and idiosyncracies, and I generally see more bugs in the async parts of our code at work. Maybe I’m just old, but I don’t think it’s worth it. Syntactic sugar over continuations/closures basically..
- kibwen 1y ago> Code that looks synchronous, but is really async, has funny failure modes and idiosyncracies But this appears to be describing languages with green threads, rather than languages that make async explicit.
- 1y ago
- dec0dedab0de 1y agoIt's had async way longer than 10 years. multi-threading/processing, celery, twisted, others I can't remember. Asyncio means learning different syntax that buys me nothing over the existing tools. Why would I bother?
- deleted 1y ago[deleted]
- northisup 1y agobecause two colors of functions suuuuuuuuuuks to deal with
- Analemma_ 1y agoDoesn't really explain why async/await are hugely popular in C#, JavaScript, etc. but didn't take off in Python.
- topspin 1y agoI'd explain your cases this way: C# has a dictator with a budget: Microsoft integrated async into C# in a formal way, with 5.0, including standard libs, debugging, docs, samples, clear guidance going forward, etc. What holes there were were dealt with in an orderly and timely manner. JavaScript actually had a pretty messy start with async, with divergent conventions and techniques. Ultimately this got smoothed out with language additions, but it wasn't all that wonderful in the early days. Also, JavaScript started from a simpler place (single-threaded event loop) that never had "fork" and threads and all that comes with those, so there was less legacy to accommodate and fewer problems to overcome. Python had a vast base of existing non-async software chock full of blocking code, plus an incomplete and haphazard concurrency evolution. There are several legacy concurrency solutions in Python, most still in use today. Python async is still competing and conflicting with it all. Not unlike the Python 2->3 transition.
- silverwind 1y agoI think Python needs a good `fetch`-like async http client in the stdlib.
- rcarmo 1y agoI personally recommend aiohttp. Setting up a ClientSession and letting it do its thing is quite nice.
- operator-name 1y agohttpx also supports sync and async, but I remember seeing an issue in their repo about worse performance than aiohttp.
- deleted 1y ago[deleted]
- OutOfHere 1y agoWith the newest Python, I can use no-gil, so my threads automatically use multiple cores. With asyncio, even under no-gil, unless I use a base layer that offers parallelism, I am stuck to a single core by default, which doesn't make any sense in a multicore world. In contrast, with Rust's async, there is no such limitation. The traditional argument against the above assertion has been that asyncio is good for I/O work, not for CPU work, but this constraint is not realistic because CPU usage is guaranteed to creep in. In summary, I can use threading/process/interpreter pools and concurrent futures, considering I need them anyway, without really needing to introduce yet another unnecessary concurrency paradigm (of asyncio).
- rcarmo 1y agoYou should look into the various Pool classes. Back when asyncio came about, I did a lot of experimenting with various multi-core approaches: https://github.com/rcarmo/newsfeed-corpus https://github.com/rcarmo/newsfeed-corpus
- deleted 1y ago[deleted]
- deleted 1y ago[deleted]
- rcarmo 1y agoI've had no real issues with async, although I primarily use libraries like aiohttp and aiosqlite and even write my own helpers (https://github.com/rcarmo/aioazstorage https://github.com/rcarmo/aioazstorage is a good example). The vast majority of the Python code I wrote in the last 5-6 years uses asyncio, and most of the complaints I see about it (hard to debug, getting stuck, etc.) were -- at least in my case -- because there were some other libraries doing unexpected things (like threading or hard sleep()). Coming from a networking background, the way I can deal with I/O has been massively simplified, and coroutines are quite useful. But as always in HN, I'm prepared for that to be an unpopular opinion.
- JackSlateur 1y agoI share your experience asyncio is easier than threads or multiprocess: less locking issue, easier to run small chunks of code in // (easier to await something than to create a thread that run some method)
- zelphirkalt 1y agoThere is no locking issue, if you don't mutate some global state from more than 1 thread at the same time. If you program mostly in pure functions, this is a non issue.
- whalesalad 1y agoI adopted gevent/greenlets pretty early on and it has always felt better than asyncio, monkey-patching aside.
- rybosome 1y agoI suppose my negative experiences with async fall under #3, that it is hard to maintain two APIs. One of the most memorable "real software engineering" bugs of my career involved async Python. I was maintaining a FastAPI server which was consistently leaking file descriptors when making any outgoing HTTP requests due to failing to close the socket. This manifested in a few ways: once the server ran out of available file descriptors, it degraded to a bizarre world where it would accept new HTTP requests but then refuse to transmit any information, which was also exciting due to increasing the difficulty of remotely debugging this. Occasionally the server would run out of memory before running out of file descriptors on the OS, which was a fun red herring that resulted in at least one premature "I fixed the problem!" RAM bump. The exact culprit was never found - I spent a full week debugging it, and concluded that the problem had to do with someone on the library/framework/system stack of FastAPI/aiohttp/asyncio having expectations about someone else in the stack closing the socket after picking up the async context, but that never actually occurring. It was impenetrable to me due to the constant context switching between the libraries and frameworks, such that I could not keep the thread of who (above my application layer) should have been closing it. My solution was to monkey patch the native python socket class and add a FastAPI middleware layer so that anytime an outgoing socket opened, I'd add it to a map of sockets by incoming request ID. Then when the incoming request concluded I'd lookup sockets in the map and close them manually. It worked, the servers were stable, and the only follow-up request was to please delete the annoying "Socket with file descriptor <x> manually closed" message from the logs, because they were cluttering things up. And thus, another brick in the wall of my opinion that I do not prefer Python for reliable, high-performance HTTP servers.
- deleted 1y ago[deleted]
- Scramblejams 1y ago> it is hard to maintain two APIs. This point doesn't get enough coverage. When I saw async coming into Python and C# (the two ecosystems I was watching most closely at the time) I found it depressing just how much work was going into it that could have been productively expended elsewhere if they'd have gone with blocking calls to green threads instead. To add insult to injury, when implementing async it seems inevitable that what's created is a bizarro-world API that mostly-mirrors-but-often-not-quite the synchronous API. The differences usually don't matter, until they do. So not only does the project pay the cost of maintaining two APIs, the users keep paying the cost of dealing with subtle differences between them that'll probably never go away. > I do not prefer Python for reliable, high-performance HTTP servers I don't use it much anymore, but Twisted Matrix was (is?) great at this. Felt like a superpower to, in the oughties, easily saturate a network interface with useful work in Python.
- Areading314 1y agoI think explicit management of the event loop and the associated potential for grievous bugs has a lot to do with it.
- lstodd 1y agoidk stackless dates back to 2005 at least, most likely earlier. greenlet which is sort of minimal stackless .. before 2008 pycoev which is on one hand greenlets without memmove()s, on the other hand sort of io-scheduled m:n threading I wrote myself in 2009. so, at least idk, 20 years? It was first needed. Then 10 years passed, people got around to pushing it through the process aaand by the time it was done it was already not needed. so it all stalled. Same with Rust. Nowadays server-side async is handled very differently. And client-side is dominated by that abomination called JS.
- toolslive 1y agoI never understood why stackless wasn't more popular. It was rather nice, clean and performant (well, it's still python but it provide(d) proper concurrency)
- lstodd 1y agoIt was memmove() on each task switch. So you could forget about d-cache. And that killed performance on anything but benchmarks.
- ack_complete 1y agoAlso caused subtle bugs. I once had to debug a crash in C++ code that turned out to be due to Stackless Python corrupting stack state on Windows. OutputDebugString() would intermittently crash because Stackless had temporarily copied out part of the stack and corrupted the thread's structured exception handling chain. This wasn't obvious because this occurred in a very deep call stack with Stackless much higher up, and it only made sense if you knew that OutputDebugString() is implemented internally by throwing a continuable exception. The more significant problem was that Stackless was a separate distribution. Every time CPython updated, there would be a delay until Stackless updated, and tooling like Python IDEs varied in whether they supported Stackless.
- lstodd 1y ago
- mjd 1y agoI haven't read the article yet, but I do have something to contribute: several years ago I was ay PyCon and saw a talk in which someone mentioned async. I was interested and wanted to learn to use it. But I found there was no documentation at all! The syntax was briefly described, but not the semantics. I realized, years later, that the (non-)documentation was directed at people who were already familiar with the feature from Javascript. But I hadn't been familiar with it from Javascript and I didn't even know that Javascript had had such a feature. So that's my tiny contribution to this discussion, one data point: Python's async might have been one unit more popular if it had had any documentation, or even a crossreference to the Javascript documentation.
- notatoad 1y agothis was my initial experience with python async as well (which i now use heavily) the documentation is directed at people who want coroutines and futures, and know what that means. if you don't know what coroutines and futures are, the python docs aren't going to help you. the documentation isn't going to guide anybody into using the async features who aren't already seeking them out. and maybe that's intentional, but it's not going to grow adoption of the async features.
- int_19h 1y agoFWIW Python got async/await before JavaScript did. I believe at the time the main inspiration was C#.
- lyu07282 1y agoJavaScript was always single-threaded asynchronous, the added async/await keywords were just syntactic sugar. Node.js became popular before it as well, though I found at the time it was difficult to avoid callback hell similar to using libuv directly in C.
- int_19h 1y agoasync/await was syntactic sugar in C# as well. Callbacks are a natural way to do async so it's no surprise. And while Python implements async directly in the VM, its semantics is such that it can be treated as syntactic sugar for callbacks there also.
- dekhn 1y agoIt added intrusive- codebase-wide- functionality that more or less could have been done with other (thread-based) approaches. AWSCLI was broken for over a year- we had to do a ton of work to deal with the various packaging issues. Don't break userspace.
- AtlasBarfed 1y agoWhy was awscli written in python? Bad decision to begin with. Hey! We have a product that we clearly want to release worldwide. Let's build it on something that doesn't have Unicode. Or any real threading. And is slow as hell. You picked a platform that was going to have to break user space. At least it wasn't JavaScript
- fzzzy 1y agoDoesn’t have Unicode? What the heck?
- mdaniel 1y agoI believe they're discussing that awscli was targeting Python 2.x for the longest time, e.g. https://github.com/aws/aws-cli/blob/0.4.1/setup.py#L48 https://github.com/aws/aws-cli/blob/0.4.1/setup.py#L48 up through https://github.com/aws/aws-cli/blob/1.19.112/setup.py#L64 https://github.com/aws/aws-cli/blob/1.19.112/setup.py#L64 from 4 years ago, seemingly cutting over to Py3-only starting with https://github.com/aws/aws-cli/blob/1.20.0/setup.py#L62 https://github.com/aws/aws-cli/blob/1.20.0/setup.py#L62 I didn't go digging into it, but I'd guess they used the ubiquitous "six" library for backporting unicode functionality, but the point is likely "but why start underwater?!"
- mdaniel 1y agoI guess at least they're consistent (or maybe herd mentality) since both azure-cli and gcloud are both in python, too
- mdaniel 1y agobut, hey, at least they get to be ultimately dynamic, leading to horeshit like this https://github.com/aws/aws-cli/blob/2.28.22/awscli/botocore/client.py#L98-L109 https://github.com/aws/aws-cli/blob/2.28.22/awscli/botocore/... What does `create_client` return?! don't you worry your pretty head about it, it'll be whatever you want it to be! flexability!!11
- ilaksh 1y agoThere is a fundamental misunderstanding about popularity. People think that popularity is directly related to merit or rationality. Technical things are largely popular for the same reason non-technical things are popular: trends. In other words, they are popular because other people perceive them to be popular. Humans are herd animals. async is harder and associated with Node.js/JavaScript which probably makes it uncool for a certain influential python subculture. But actually Fast API has basically taken over and now I think people should recognize that means async IS popular in python at this point.
- ketchupdebugger 1y agoThe two api issue basically means async is not backwards compatible. You can't just squeeze some async into an existing code base, You'd need new functions, libraries etc. You'd basically need to rewrite the entire codebase in async to see an ounce of perf improvements.
- svieira 1y agoI used to keep plugging Unyielding [1] vs. What Color Is Your Function [2] as the right matrix to view these issues within. But then Notes on structured concurrency [3] was written and I just point to that these days. But, to sum it all up for those who want to talk here, there are several ways to look at concurrency but only one that matters. Is my program correct? How long will it take to make my program correct? Structured concurrency makes that clear(er) in the syntax of the language. Unstructured concurrency requires that you hold all the code in your head. [1]: https://glyph.twistedmatrix.com/2014/02/unyielding.html https://glyph.twistedmatrix.com/2014/02/unyielding.html [2]: https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/ https://journal.stuffwithstuff.com/2015/02/01/what-color-is-... [3]: https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/ https://vorpus.org/blog/notes-on-structured-concurrency-or-g...
- heisenzombie 1y agoI'll second the plug for structured concurrency (and specifically the Trio [1] library that the author wrote. [1] https://github.com/python-trio/trio https://github.com/python-trio/trio
- vpribish 1y agoIf I ever want to use async in python again i'm going with Trio.
- stephenlf 1y agoMan, that Trio [3] read was great. When we demand that all concurrent tasks must join, then we can better reason about our programs. I already kinda had this idea while working with Rust. In Rust, Futures won’t execute unless `await`ed. In practice, that meant that all my futures were joined. It was just the only way I could wrap my head around doing anything useful with async.
- VonTum 1y agoIn [3], isn't there a pretty trivial exploit to get a "background task reads from closed file" again? async with mk_nursery() as nursery: with os.fopen(...) as file: nursery.start_soon(lambda: file.read()) The with block may have ended before the task starts...
- KaiserPro 1y agothe two issues I have with async is are: 1) its infectious. You need to wrap everything in async or nothing. 2) it has non-obvious program flow. Even though it is faster in a lot of cases (I had a benchmark off for a web/socket server for multi-threaded vs async with a colleague, and the async was faster.) for me it is a shit to force into a class. The thing I like about threads is that the flow of data is there and laid out neatly _per thread_, where as to me, async feels like surprise goto. async feels like it accepts a request, and then will at some point at the future either trigger more async, or crap out mixing loads of state from different requests all over the place. To me it feels like a knotted wool bundle, where as threaded/multi-process feels like a freshly wound bobbin. Now, this is all viiiiiibes man, so its subjective.
- bmandale 1y agoI don't like the idea of launching a whole thread for every concurrent task I want to do. But holy hell is it so much easier than figuring out how tf async works. If I wanted something super performant I wouldn't be using python in the first place.
- rdtsc 1y agoI never liked async in Python. I feel like it's a bad design pattern, a lot of borrowed from Twisted at the time. I always liked gevent/eventlet based approach and will likely always stick to using that. At the time Go and Elixir/Erlang had green threads (lightweight procs / goroutines) and in general I think that makes for a cleaner code base.
- cyberax 1y agoTo add to this, async in Python is also plain buggy. For example, uvicorn is the most popular FastAPI server, and it leaks contexts across requests in the default installation. The bug has been open for 2 years, with zero fucks given. The workaround is "just use libuv": https://github.com/encode/uvicorn/issues/2167 https://github.com/encode/uvicorn/issues/2167 I've seen other such cases, and I just gave up on trying to use async.
- rsyring 1y agoNot too long ago, I read a comment on HN that suggested, due to Python's support for free-threading, async in Python will no longer be needed and will lose out to free-threading due to it's use of "colored" functions. Which seems to align with where this author ends up: > Because parallelism in Python using threads has always been so limited, the APIs in the standard library are quite rudimentary. I think there is an opportunity to have a task-parallelism API in the standard library once free-threading is stabilized. > I think in 3.14 the sub-interpreter executor and free-threading features make more parallel and concurrency use cases practical and useful. For those, we don’t need async APIs and it alleviates much of the issues I highlighted in this post. Armin recently put up a post that goes into those issue in more depth: https://lucumr.pocoo.org/2025/7/26/virtual-threads/ https://lucumr.pocoo.org/2025/7/26/virtual-threads/ Which lead me to a pre-PEP discussion regarding the possibility of Virtual Threads in Python, which was probably way more than I needed to know but found interesting: https://discuss.python.org/t/add-virtual-threads-to-python/91403 https://discuss.python.org/t/add-virtual-threads-to-python/9...
- ashf023 1y agoInteresting that very few people in that thread seem to understand Go's model, especially the author of this proposal. If you don't allow preemption, you still have a sort of coloring because most non async functions aren't safe to call in a virtual thread - they may block the executor. If you call C code, you need to swap out stacks and deal with blocking by potentially spawning more OS threads - that's what CGo does. Maybe preemption is harder in Python, but that's not clearly expressed - it's just rejected as obviously unwanted. Ultimately Python already has function coloring, and libraries are forced into that. This proposal seems poorly thought out, and also too little too late.
- rsyring 1y agoI can't speak to the more technical aspects you bring up b/c I'm not that well versed in the underlying implementations and tradeoffs. > and also too little too late. I think it very likely that Python will still be around and popular 10 years from now. Probably 20 years from now. And maybe 30 years from now. I think that's plenty of time for a new and good idea that addresses significant pain points to take root and become a predominant paradigm in the ecosystem. So I don't agree that it's too little too late. But whether or not a Virtual Threads implementation can/will be developed and be good enough to gain wide adoption, I just can't speak to. If it's possible to create a better devx than async and get multi-core performance and usage, I'm all for the effort.
- fulafel 1y agoI think this is for the best. We don't want to end up like Rust. The complexity tradeoff suits Python's sweet spot even less (much less).
- xg15 1y agoI learned about the concept of async/await from JS and back then was really amazed by the elegance of it. By now, the downsides are well-known, but I think Python's implementation did a few things that made it particularly unpleasant to use. There is the usual "colored functions" problem. Python has that too, but on steroids: There are sync and async functions, but then some of the sync functions can only be called from an async function, because they expect an event loop to be present, while others must not be called from an async function because they block the thread or take a lot of CPU to run or just refuse to run if an event loop is detected. That makes at least four colors. The API has the same complexity: In JS, there are 3 primitives that you interact with in code: Sync functions, async functions and promises. (Understanding the event loop is needed to reason about the program, but it's never visible in the code). Whereas Python has: Generators, Coroutines, Awaitables, Futures, Tasks, Event Loops, AsyncIterators and probably a few more. All that for not much benefit in everyday situations. One of the biggest advantages of async/await was "fearless concurrency": The guarantee that your variables can only change at well-defined await points, and can only change "atomically". However, python can't actually give the first guarantee, because threaded code may run in parallel to your async code. The second guarantee already comes for free in all Python code, thanks to the GIL - you don't need async for that.
- Retr0id 1y ago> some of the sync functions can only be called from an async function, because they expect an event loop to be present I recognise that this situation is possible, but I don't think I've ever seen it happen. Can you give an example?
- xg15 1y agoEverything that directly interacts with an event loop object and calls methods such as loop.call_soon() [1]. This is used by most of asyncio's synchronization primitives, e.g. async.Queue. A consequence is that you cannot use asyncio Queues to pass messages or work items between async functions and worker threads. (And of course you can't use regular blocking queues either, because they would block). The only solution is to build your own ad-hoc system using loop.call_soon_threadsafe() or use third-party libs like Janus[2]. [1] https://github.com/python/cpython/blob/e4e2390a64593b33d65567179265f9c2cd9acae1/Lib/asyncio/base_events.py#L817 https://github.com/python/cpython/blob/e4e2390a64593b33d6556... [2] https://github.com/aio-libs/janus https://github.com/aio-libs/janus
- alanfranz 1y agoMuch more than 10y. Twisted existed since the 90s. I didn’t read the whole article but I find is strange that it’s not mentioned, ever.
- nromiun 1y agoIt was supposed to bring massive concurrency to Python. But as with any async implantation in any language it is too easy to deadlock the entire system. Did you forgot to sprinkle enough `await`? Your code is blocked somewhere, good luck hunting for it. In contrast preemptive green threads are too easy. Be it IO or CPU load all threads will get their slice of CPU time. Nothing is blocked so you can debug your logic errors instead of deadlocks everywhere. Async works in JS so well because the entire language is designed for it, instead of async being just bolted on. You can't even run plain `sleep` to block, you need setTimeout.
- DanielHB 1y agoIt is even funnier because JS only got proper async after, what? 25 years or so of existence. The main reason JS went all in with async is because it only ever had a single event loop and that naturally fits with the async model. I still remember the days when all the libs started adopting async and how so many of them (to this day) support both passing callbacks or returning promises. Async just so naturally fixed the callback hell of 2010s JS that it just became standard even though it is not even heavily used in the browser APIs.
- KingOfCoders 1y agoWhat I find funny is Java started with green threads, then moved away to system threads, then back again.
- nromiun 1y agoMaybe massive concurrency was not that big of a feature back then. But these days everyone wants to support a million connections at a time. Green threads and async tasks can do that without breaking a sweat, unlike OS threads. Also, Java virtual threads are still cooperative. Maybe they will move to preemption in time like Go did. Some time ago I tried to run just 10k OS threads on a small PC and it just crashed. So clearly OS threads have not improved much.
- th0ma5 1y agoI adopted just the Clojure style of thinking in terms of immutable copies and it seems easier to move between synch and asynch conceptually as needed, although Clojure has some asynch parallelism automatically due to this paradigm as well.
- Meneth 1y agoKeyboardInterrupt (Ctrl+C) has been a problem wherever I've used python async. It should just work out of the box.
- JodieBenitez 1y agoWhy isn't it more popular ? Well, replacing libs and functions with async versions is not fun.
- languagehacker 1y agoWow, didn't even see much about how miserable using the sync_to_async and async_to_sync transformers are. In general, the architectures developed because of the GIL, like Celery and gunicorn and stuff like that, handles most of the problems we run into that async/await solves with slightly better horizontal scaling IMO. The problem with a lot of async code is that it tends not to think beyond the single machine that's running it, and by the time you do, you need to rearchitect things to scale better horizontally anyway. For most Python applications, especially with web development, just start with something like Celery and you're probably fine.
- operator-name 1y agoNot to mention sync_to_async and async_to_sync are also part of a library, asgiref that the Django developers made to wrap a thread pool runtime!
- andrewstuart 1y agoNot popular? I use async all the time. The evidence this post provides is that flask and Django aren’t all in on async. That’s meaningless.
- kamikaz1k 1y agoif you're going to lobby that criticism, you should atleast offer an alternative definition of popular...unless you're saying your usage of a tool defines its popularity
- the__alchemist 1y agoThe barrier it places in Rust's lib ecosystem is unpleasant; I'm glad it hasn't taken off in Python. I have written too many rust libs because the existing ones forced your code to be Async.
- bigstrat2003 1y agoThe bifurcation of the Rust ecosystem due to async makes me absolutely loathe the feature, and wish it had never been added to the language. It's so awful.
- omnicognate 1y agoFor a counter-opinion that isn't getting stated much here, I think: * Asyncio is pretty good, and is usually the best choice for non-blocking I/O in python these days. * Asyncio doesn't add multi-core scaling to python. It's not a replacement for threads and doesn't lift the GIL-imposed scaling limitations. If these things are what you're after from asyncio you'll be disappointed, but they're not what it's trying to add and not adding them doesn't make it a failure. * "Coloured functions" is a nonsense argument and that article made the whole world slightly more dumb. * The GIL is part of the reason for python's success. I hope nogil either somehow manages to succeed without compromising the benefits the GIL has brought (I'll be amazed if that happens) or fails entirely. Languages are tools and every tool in your toolbox doesn't have to eventually turn into a drill. If your use case requires in-process parallelisation of interpreted CPU-bound workloads across multiple cores, python is just the wrong thing to use. * It is indeed extremely annoying that we don't have async file access yet. I hope we get it soon.
- TZubiri 1y agoBecause I don't need it. When I need to do concurrent stuff I either use fork to multiprocess or use the threading library, no import necessary, couple of lines of code, no need to make specialized code with await keywords and stuff. This line made me question myself though: "Then Flask is and probably always will be synchronous (Quart is an async alternative with similar APIs)." I use flask, and I literally spent the last hour questioning whether I was an idiot and needed to dm my previous clients asking them to fix my code. I'm wondering how my apps passed stress tests of thousands of concurrent users, maybe I did the tests wrong? Chatgpt says "s flask asynchronous? ChatGPT said: Flask itself is not asynchronous. It is a WSGI-based framework, which means it is synchronous by design — it handles one request at a time per worker. Each request is processed sequentially, and concurrency is typically achieved by running multiple worker processes" Oh shit, I didn't use gunicorn, I just run the python script raw. I'm an idiot. Let's write a test server that sleeps for 1 second before responding to a request: " import flask import requests import time app = flask.Flask("test") @app.route("/") def hi(): time.sleep(1) #requests.get("https://google.com https://google.com") return "Hello, World!" app.run("0.0.0.0",8088) " This should block for like 25ms, if 50 concurrent users ask for this resource, there will be an average 500ms of extra latency! And a Test client that does 50 calls at once, will it take 50 seconds?: "import threading import requests URL = "http://127.0.0.1:8088/ http://127.0.0.1:8088/" def make_request(i): try: print("req") response = requests.get(URL) print("res") except: print("fail") threads = [] for i in range(5): t = threading.Thread(target=make_request, args=(i,)) threads.append(t) t.start() for t in threads: t.join() print("All requests completed") " Then we run with time binary in linux: >time python3 client.py All requests completed real 0m1.216s user 0m0.203s sys 0m0.039s Ok, turn off the alarms, Flask is fine. I'm not sure what's going on with async, but the only experience I had with it was a junior dev that came from writing horrible node apps with react and nest (his frontend connected to a supabase db directly with credentials exposed, even if there was a node backend). He wanted to pivot to python because that's what I used and I had good results, so he installed Quartz instead of Flask, and he was writing Node like code in python, and it was of course a mess. Not saying that it's always going to be a mess, but you are better off learning the native way of a language instead of trying to shoehorn other abstractions and claiming that the way it is done in python is inefficient, it's one of the most popular languages in the world, these are massively used libraries, it's unlikely that "something is terribly wrong". It's more of a meme that python is slow. What async is, is an alternative and supposedly cleaner abstraction to do multithreading. What ends up happening is that people use it without understanding multithreading and operating systems in general, they just think that they need to use it to get parallelism. There's 15 solutions to do parallelism, 1 is the native, vanilla solution (threading library), then there's 3 additional experimental ways in the standard library or futures library, and 11 solutions that you need to pip install. Newbies ask chatgpt or see a stackoverflow thread (or come from node), and they have a 1 in 15 chance of using the regular solution that newbies should be using, because they can't distinguish the wheat from the chaffe. OP might have suffered from this and even believed that this 15th "async" way to do concurrency was the only way, and is judging python's concurrency by this feature. OP maybe believes that python is just now getting multithreading support? That we are all cavemen running toy applications that server 2 or 3 users? Word to the wise, focus on features that have existed on early versions like python2 BEFORE you focus on features that are being introduced in the later versions like 3.14, this in general, you should first learn how a UNIX machine from the 90s did its thing before you learn the kubernetes spark majiggy
- foresto 1y agoA little history... During development, asyncio was called tulip. A quick search turns up this talk by Guido: https://www.youtube.com/watch?v=aurOB4qYuFM https://www.youtube.com/watch?v=aurOB4qYuFM I seem to recall that Guido was in touch with the author of Twisted at the time, so design ideas from that project may have helped shape asyncio. https://twisted.org/ https://twisted.org/ Before asyncio, Python had asyncore, a minimal event loop/callback module. I think it was was introduced in Python 1.5.2, and remained part of the standard library until 3.12. https://docs.python.org/3.11/library/asyncore.html https://docs.python.org/3.11/library/asyncore.html https://docs.python.org/3.11/library/asynchat.html https://docs.python.org/3.11/library/asynchat.html
- blibble 1y agoasyncore actually worked well, unlike asyncio so of course in their infinite wisdom, they removed it
- lormayna 1y agoI always considered the ergonomic of async/await not really ergonomical and hard to debug. I really like, indeed, the go approach: using goroutines, channels and waitgroups is powerful and easy.
- OhMeadhbh 1y agoI'm not the biggest Python fan, but when I was forced to use it using async disabled a bunch of things... like the debugger. Not a fan.
- bjt 1y agoI was using gevent to get async benefits in Python 10+ years ago. It's a much nicer programming paradigm than async/await, in my opinion. Now working in Go where the same pattern is built into the language, I'm even more convinced.
- kurtis_reed 1y agoThe premise of the article is wrong. Async in Python is popular. I'd expect most new web backends to use it. The article says SQLalchemy added async support in 2023 but actually it was 2020.
- jpgvm 1y agoBecause they chose the wrong API (well more correctly created a new, worse one). In order to appease the various flavours they mixed and matched stuff from Tornado, gevent, etc. They should have stuck with the most seamless of those (gevent) and instead of having it monkey-patch the runtime go the Java VirtualThread route and natively yield in all the I/O APIs. This would have given a Go-esque ease of use and likely would have been immensely more popular.
- odyssey7 1y agoPython is ergonomically challenged, so we shouldn’t be surprised when features built on that foundation go unused.
- throwawayffffas 1y agoThe function coloring is a non starter for me. I would just rather write JS where everything is async by default.
- IshKebab 1y agoEverything is not async by default in JS.
- throwawayffffas 1y agoI mean everything is running on the runloop, async/await, promises, and callbacks are different flavors of syntactic sugar for the same underlying thing. In JS you can do: async function foo(){...} function bar(){foo().then(...);} In python though async and sync code runs in a fundamentally different way as far as I understand it.
- IshKebab 1y agoI'm not too familiar with Python async. The only time I used it was to get stderr and stdout out of a subprocess.run() separately. I think anyone using it for performance reasons is insane and should just switch to a more performant language. Anyway I think the main difference is that in Python you control the event loop whereas in JS there's one fixed event loop and you have no choice about it.
- fzzzy 1y agoI think what they mean is that there are no blocking functions in the standard library except alert, prompt, and confirm. ( are there any others?)
- steve_adams_86 1y agoYeah, you can call async functions without specifying it as such and the script will just carry on regardless of how you're handling it. Totally weird, but also pretty cool. When I first started some 20 years ago that was a major foot gun for me, coming from PHP where functions always returned before the next one was called.
- 6510 1y agoI've always felt like there is some hidden clue in music trackers. They program the music as spaghetti code with unlimited channel running neatly along the same line numbers.
- ayaros 1y agoI love JS's async. I don't know how anyone ever did anything useful in the language before it was introduced. I think something between a third and half of the functions and members in LisaGUI are probably async functions at this point.
- steve_adams_86 1y agoWe used callbacks and generators. It was a bit messy at times, but really, it wasn't all that different. I still use generators quite often.
- ayaros 1y agoOh... only a "bit" messy, you say? ;)
- steve_adams_86 1y agoHaha, yeah. I didn't find generators messy at all, but callbacks led to the term 'callback hell' for good reason. I think there's a good reason as well that async generators are at the core of async/await, but people rarely use them outside of abstractions. I like them, but they are a lower level tool for sure. Once they 'click' and you feel good with them, great, but chances aren't very good that everyone you work with will feel the same. Generators add on a sort of cognitive overhead more than mess, I guess. Sometimes it makes sense to pull them out, but often it doesn't. Promises probably encapsulate 95% of common use cases. Promises just do one thing, whereas everywhere you use generators, you've got all the power and potential of generators. Kind of a 'great power, great responsibility' problem
- didip 1y agoIt would have been a lot more popular if it has a shim that lets it pretend to be a regular thread. Folks don't like to perform a lot of rewrites.
- cyberax 1y agoAnother thing: the lack of JIT. NodeJS is also single-threaded, but it's _fast_ because of one of the best JITs in the industry. So you can feasibly run hundreds if not thousands requests per second on one core. If you try to do that with Python, you get performance that is not acceptable. So why even bother?
- game_the0ry 1y agoI will take a couple stabs: - Async is a legitimately hard to get if you are just starting to learn it, which is probably why its isn't more popular in the python community. - If you need async, that implies you need hi I/O performance. At that point, you probably should have picked a more performant language + runtime (Java, Node), bc use case should dictate tooling. - It's not enough to make a language + web framework to be async -- the DB drivers need to be async too (author mentions sqlalechemy got async support in 2023 and django orm is a WIP). I like python, but not bc its async or multi-threaded. I like it bc when I use it, I know I do not have to worry about those things and the new set of problems I have to handle when I do. For the i/o and multi-threaded perf, give me java and node (maybe erlang/elixir if I am feeling extra spicy). For the fast and easy scripting, with massive community of open source of talent and high quality libraries (including the vast majority of web app slop), give me python.
- hoppp 1y agoTo be frank someone who picks python is not doing it because they want the best performance. Its either because its the only language they know or they just don't really care about performance and want to finish the project fast.
- game_the0ry 1y agoAgreed, bc I have been that "someone." And there is nothing wrong with that. In fact, this should be the norm.
- taeric 1y agoWouldn't this be like asking why bit packing/flipping isn't more popular in python? In general, it just isn't necessary for the vast majority of programs people are likely to write using python. Which isn't to argue that they did a good or a bad job adding the ability to the language. It just isn't the long pole in performance concerns for most programs.
- TheCondor 1y agoI generally like Python. I'm not a hater but I don't treat it like a religion either. Async Python is practically a new language. I think for most devs, it's a larger than than 2 to 3 was. One of the things that made python uptake easy was the vast number of libraries and bindings to C libraries. With async you need new versions of that stuff, you can definitely use synchronous libraries but then you get to debug why your stuff blocks. Async Python is a different debugging experience for most python engineers. I support a small handful of async python services and think it would be an accellerator for our team to rewrite them on Go. When you hire python engineers, most don't know async that well, if at all. If you have a mix of synchronous and asynchronous code in your org, you can't easily intermix it. Well you can, but it won't behave as you usually desire it to, it's probably more desirable to treat them as different code bases. Not to be too controversial, but depending upon your vintage and they was you've learned to write software I think you can come to python and think async is divine manna. I think there are many more devs that come to python from datascience or scripting or maybe as a first language and I think they have a harder time accepting the value and need of async. Like I said above, it's almost an entirely different language.
- tonymet 1y agoasync only helps with io-wait concurrency, but not cpu-bound concurrency. async is popular in JS because the browser is often waiting on many requests. command-line tools are commonly computing something. even grep has to process the pattern matching so concurrent IO doesn't help a single-threaded pattern match. Sure there are applications where async would help a CLI app, but there are fewer than JS. Plus JS devs love rewriting code very 3 months.
- liquidpele 1y agoBecause it’s terrible. People don’t avoid non-terrible things.
- matthew16550 1y agoPythons builtin async always confuses me. The Trio library felt easy to learn and just worked without much fuss. https://trio.readthedocs.io/ https://trio.readthedocs.io/
- bilsbie 1y agoHow does this jive with the GIL?
- dagenix 1y agoThe problem, IMO, with asyncio is that its way, way too complicated. In my experience, anyio (https://github.com/agronholm/anyio https://github.com/agronholm/anyio) provides a much better interface on top of asyncio. And since it can use asyncio as a backend, it maintains compatibility with the asyncio ecosystem. FastAPI, for example, uses anyio. One thing that I don't see being mentioned in any of the threads here talking about green threads is cancellation. A huge benefit, IMO, of anyio is that it makes cancellation really easy to handle. With asyncio, cancellation is pretty hard. And with green threads, cancellation is often impossible.
- 0xbadcafebee 1y agoBecause it's a niche? You don't need async for most stuff Python is used for, it's a "nice-to-have", and it's annoying to add. If you have to have concurrency/threading/etc, there are other languages with better paradigms. The same thing happened with Perl and its weird threading (for different reasons, but still)... I guess Python didn't learn that lesson. Perl also gained async and coroutine support, but I think they were added a while after I left the community. I doubt many people use them today. Anyone used them and can comment on ease vs Python?
- rich_sasha 1y agoAsync is perfectly fine for a medium-load single-threaded RPC/REST server wrangling. Ran it in production with 100s, sometimes 1000s of calls / sec with no issues. And thread-safety is much easier with async, where you know where the context switches are occuring.
- breatheoften 1y agoThe problem with python's async is asyncio ... Structured concurrency libraries like anyio or trio are actually pretty nice -- "stacks" and stack traces are good things. Python multi exception concept is weird --- but also I think probably good ish. It is still a pita to orchestrate around the gil/how terrible python multiprocessing side effects are wherever cpu bound workloads actually exist ...
- est 1y ago> Problem 3: Maintaining two APIs is hard Well I had a fix https://news.ycombinator.com/item?id=43982570 https://news.ycombinator.com/item?id=43982570
- deleted 1y ago[deleted]
- zbentley 1y agoI don't love Python's async API either, but I think a lot of its complained-about complexity arises from two things: making "when does the coroutine start running" a very explicit point in code (hence the Task/awaitable-function dichotomy), and how it chooses to handle async cancellation: via exceptions. And Python's async cancellation model is pretty nice! You can reason about interruptions, timeouts, and the like pretty well. It's not all roses: things can ignore/defer cancellations, and the various wrappers people layer on make it hard to tell where, exactly, Tasks get cancelled--awaitable functions are simple here, at least. But even given that, Python's approach is a decent happy medium between Node's dangling coroutines and Rust's no-cleanup-ever disappearing ones (glib descriptor: "it's pre-emptive parallelism, but without the parallelism"). More than a little, I think, of the "nobody does it this way" weirdness and frustration in Python asyncio arises from that. That doesn't excuse the annoyances imposed by the resulting APIs, but it is good to know.
- rich_sasha 1y agoCancellations probably caused more bugs in my async code than anything else. If any code in your coroutine, including library code, has a broad try/except, there's good chances that eventually the cancellation exception will be swallowed up and ignored. Catch-all try/except of course isn't the pinnacle of good software engineering, but it happens a lot, in particular in server-tyoe applications. You may have some kind of handler loop that handles events periodically, and if one such handling fails, with an unknowabl exception, you want to log it and continue. So then you have to remember to explicitly reraise cancellation errors. Maybe it's the least bad Pythonic option, but it's quite clunky for sure.
- wodenokoto 1y ago> If you call function get_thing_sync() versus await get_thing_async(), they take the same amount of time. No, if you call both function one will try and fetch a none responding url and the other will immediately raise an exception.
- rich_sasha 1y agoWhat the article and the comments don't seem to mention is also that the documentation is an outlier on the poor side. Most Python documentation is at least decent. asyncio hides a lot of the complexity behind a tutorial style "just do this" prose, only obliquely mentions the foot guns and gives little guidance on how to actually structure async code. IME writing an asyncio Python application is a bit like fixing a broken Linux boot. You frantically Google things, the documentation doesn't mention it, and eventually you find a rant on a forgotten Finnish embedded electronics forum where someone has the same problem as you, and is kindly sharing a solution. After 30 mins of C&P of random commands from a stranger on the web, it works, for no reason you can decipher. Thank goodness for the Finns and Google Translate.
- bertil 1y agoThis rings incredibly true, with one major exception: Google Translate can’t handle Finnish to a point that’s both confusing and hilarious. If the output explains how asyncio works, I’m guessing the original discussion was about opening portal for demons, or waiting in line to board the ferry to Estonia.
- Philpax 1y agoI would disagree on the first paragraph, if only to say that the majority of Python stdlib documentation is written in that tutorial style, and I loathe it. It is always a chore to look something in the stdlib up, especially if you're used to the reference documentation for Rust/Go/Ruby/JavaScript.
- rich_sasha 1y agoI think a lot of standard library have both. For example multiprocessing or logging. It's true, the tutorial is annoying, except perhaps on first reading, but at least the proper documentation is there. For asyncio the actual hard documentation bit is missing, incomplete or misleading, depending on where exactly you're looking.
- Animats 1y agoPython has had threads for 20 years. Why weren't they more popular?
- KingOfCoders 1y agoI did a lot of Scala Futures and liked the concept, more than 'async' everywhere, because it was easier to reason what happens and functions were just functions. Since some years I use Go where this is even easier. But it took me some time to realize I can do the same idioms in Go as in Scala: // Scala f := Future(x) // Do something else until you need f ... for r <- f { ... } can be written as c := channel // Do something else until you need the result ... r<-c My mind model was channel as a queue, but it can easily be used like channel as a future for one value. And `select` for more complicated versions. I miss the easy composition and delaying of futures though (f.map etc.)
- harpiaharpyja 1y agoI've been working quite heavily with async Python for five and a half years now. I've been the principal developer of a control system framework for laboratory automation, written pretty much entirely in async Python. I say framework because it's a reusable engine that has gone on to become the foundation for three projects so far. Our organization is primarily involved in materials research. At it's heart it's kind of like an asynchronous task execution engine that sits on top of an I/O layer which allows the high-level code to coordinate the activities of various equipment. Stuff like robot arms, furnace PID controllers, gantry systems, an automatic hydraulic press/spot welder (in one case), various kinds of pneumatic or stepper actuated mechanisms, and of course, measurement instruments. Often there might be a microcontroller intermediary, but the vast majority of the work is handled by Python. My experience with async Python has been pretty positive, and I'm very happy with our choice to lean heavily into async. Contrary to some of the comments here I don't find the language's async facilities to be rough at all. Having cancellation work smoothly is also pretty important to us and I can't say I've experienced any pain points with exception-based cancellation. Maybe we've been lucky, but injecting an exception into a task to cancel it actually does work pretty reliably. Integrating dependencies that expose blocking APIs has never been a big deal either. Usually you want to have an interface layer for every third party dependency anyways, and it's no big to deal to just write an async wrapper that uses a threads or a thread pool to keep the blocking stuff off of the main thread. I personally think that a lot of people's negative experiences here might have more to do with asyncio than the language's async features. Prior to stepping into my current role, I also had some rough experiences with asyncio, which is why we chose to build all of our async code on top of curio. There was some uncertainty at first about how well supported it would be compared to a package in the standard library, but honestly curio is a really well put together package that just works really smoothly.
- _dain_ 1y agoOh hey, I'm the mirror universe version of you. I used to work in a semiconductor plant, writing Python code that controlled robot arms and electronic measurement instruments and so on. In my universe we used threads over blocking calls instead of async and it was exactly as bad as you might imagine. >Having cancellation work smoothly is also pretty important to us +10000. Threads don't have good cancellation semantics, so we never had a robust solution to the "emergency shutdown" problem where you need to tell all the running equipment to stop whatever they're doing and return to safe positions. Every day I worked on that codebase I wished it had been async from the beginning, but I couldn't see a way to migrate gradually because function coloring makes it an all-or-nothing affair.
- mting 1y agoI would prefer to implement it using a synchronous approach and then switch to asynchronous at deployment via kafka etc this way could simply focus on bussniss logical
- mting 1y agoI would prefer to implement it using a synchronous approach and then switch to asynchronous at deployment.
- BrenBarn 1y agoThe main reason I've encountered is that async is generally an all-or-nothing thing. It's generally not possible to take an existing code base and just "add a little async here and there". The entire thing has to be restructured from the ground up for async. The gain has to be really major for this to be worthwhile, more so the better your existing code already works. This is sort of like the article's Problem 3, but it's not just maintaining two APIs, it's even creating the second API in the first place.
- guappa 1y agoBefore async they had asyncore, which they now entirely removed. So the real early adopters of async in python are punished by having to rewrite their software to run it with a current version of python.
- nurettin 1y agoPython async feels great ergonomically at first. Async tasks, timers, things happening concurrently. But then you lose stack traces. Code that starts sync, then appends jobs to an async event queue can't be traced, because the exception happened in the loop and doesn't bubble up to sync (or it didn't back in 3.8). That, among with synchronization problems (it is an event loop, why do we even need to synchronize? async mutex??) I really tried to make it work, but eventually gave up and went back to deque. Now life is great.
- physicsguy 1y agoOne of the big reasons I'd say is that 90% of Python work doesn't actually benefit from async? Basically nothing in the data science / simulation / etc. world benefits at all. Web development it does, and Django has sprinkled it in (but not DRF), Flask has a fork that's async and FastAPI is async. At work people have suggested we should switch our Flask code to async to 'make it faster' but for us, we're largely using Flask to server ML models and so there's no benefit by being async at all since we're largely compute bound within the request cycle.
- guappa 1y agoYou'd save a bit of memory by letting 1 thread handle multiple connections, but that's about it.
- wink 1y agoI think the 2/3 split had more impact than the author thinks. Many people in my bubble (around 2013-2017) just never went with python 3, but chose other languages. The company I was working for started important applications in python 2 as late as 2014 because the libraries we needed weren't ported yet. We never went python 3 later, but went to go instead, so we completely missed any python async thing.
- notepad0x90 1y agoFor me, when I use python, it's because I want faster dev time to prove a concept or that I expect others with little to no programming experience to maintain the code in the future. So, I rarely ever use async because I never seem to be in a position where the debugging complexity and how hard it is for others/newbies to read and be familiar with the code is worth the performance improvements. Like others are saying, if I want it fast and efficient (processing), I'll just use Go. Python isn't like JS in browsers, you don't have to use it, you have to want to use it. and the same goes with its features. Maybe if python tutorials/books and "How do i ____ in python?" search results used async, map, filter, collections,etc.. these awesome python features would be more prevalent. But, I can see how mature projects should probably mandate their usage where it makes sense.
- WhyNotHugo 1y agoasync doesn't work if you need to do filesystem I/O. With POSIX, you can only really do blocking filesystem I/O. There's an API for async I/O, where readiness of any read/write operation can either deliver a signal, or start a new thread. Neither of these scale at all. Things like select, poll, epoll all block, even with O_NONBLOCK. So if your application needs to read files which may be large, or on a slow filesystem (or even networked filesystems!), you're now working with blocking I/O, at which point async can't help you. --- Obviously this isn't the root cause of "why hasn't async taken over". It's just one of the many reasons which all pile up.
- hk1337 1y agoIt's not as easy to implement as it is in javascript though. If someone has it already implemented, like say in FastAPI, then it's pretty trivial to use but to just use async is kind of a pain.
- stillsut 1y agoNot an expert but my chats with ChatGPT led me to believe async + FastAPI can give you 40x throughput for request handling over non-async code. The essential idea was I could be processing ~100 requests per vCPU in the async event loop while threading would max out 2-4 threads per CPU. Of course let us assume for either model we're waiting for 50-2000ms DB query or service call to finish before sending the response. Is this not true? And if it is true, why isn't the juice is worth the squeeze: more than an order of magnitude more saturation/throughput for the same hardware and same language, just with a new engine at its heart?
- bolangi 1y agoFor comparison, I asked about async in the raku programming language (https://rakulang.org https://rakulang.org). While I don't know details, raku's design avoids function coloring ( https://www.reddit.com/r/rakulang/comments/1n8hjrr/async_in_raku_vs_python/ https://www.reddit.com/r/rakulang/comments/1n8hjrr/async_in_...).