by VWWHFSfQ · 6y ago · 0 comments
Every new release of Python seems like it gets bigger and bigger and more and more incomprehensible. The Python 2 -> 3 transition was a (necessary?) disaster. And now we're trying, in earnest, to figure out how to get rid of the GIL. The async/await syntax is a whole other fiasco. Now we have colored functions all over the place. Python code doesn't even work with Python code. It's just an absolute mess.
I agree with the 2->3 problem. I also wish there were no GIL.
That said, python is my favorite language of them all.
I wonder if the way forward might just be to expect different incompatible versions from time to time and create robust facilities to handle it.
What do you think Lua's developers should have done differently?
What stops Lua from being used as a general-purpose scripting language?
Probably the biggest errors were the historical either/or integer/floating point numbers, and the weird PHP-like hash-tables-are-the-only-first-class-datastructure.
async / await are just primitives, they are, in no way, incompatible with the rest of Python code.
At worst, if you mix blocking and non blocking, you loose the performance benefit, that's all. It all works. You are just back to non async execution.
You can use async functions in sync code and vice-versa.
In fact, you can use async / await for asyncio, or another lib, or no lib at all, it's a completly lib agnostic concept. It doesn't even need any io. async / await is just a "yield from" which understands __await__.
It's an interface. A contract. Like generators.
What's more, the python community is now following the best pratice of creating Sans I/O libs (https://sans-io.readthedocs.io/), which means you can plug in whatever I/O lib you want.
There is a lot of confusion around asyncio, partly because of the communication and doc around it, partly because it sucked up until python 3.7, and partly because a lot of python devs have absolutely no need for it and see it from the point of view of their day to day task.
But it's definitly not fiasco, it's quite a handy tool, and the generic interface of async / await is nifty and allows cool designs.
Type hinting rocks. Use it properly everywhere and you can a lot of confidence and speed when refactoring.
I use attrs (I know there are alternatives) to get legit type checking on object fields. Yes it is runtime type checking but if you write tests, those errors will pop up before you ever run the app.
Honestly I think the priority with Python should just be around digging deep into the implementations for performance gains. I’m very happy with how the ergonomics of the language are now.
Before 3.7, you had to be able to fetch the loop, handle its reference, pass it around, manage its life cycle, etc.
Starting from 3.7, only low level code (E.G: framework authors) would need to, the API is organized so that by default, you always perform something in the current running loop.
It's a big deal, and remove a ton of complexity. Maintenance is easier, learning curve is flatter.
The best example, is that in 3.6 and lower, you had to do "loop = asyncio.get_event_loop()", then call "loop.run_until_complete()". In 3.7, you use asyncio.run(). It seems trivial, it's really not:
https://github.com/python/asyncio/blob/db2fe1d1e1d0f7352167a....
This has consequences on the whole design, which is now full of things like that (run_in_executor, create_task, run_forever, etc), changing completly the way to write correct code.
Another thing is that in 3.7, the asyncio uses async / await and not yield from. Because of this dog fooding, the whole lib improved.
3.7 has a LOT of patches just for asyncio: https://docs.python.org/3.7/whatsnew/changelog.html#python-3...
Speed (Future has been rewritten in C, and many other tweaks), fixes, _way_ better doc...
Obvious shortcomming were resolved, like asyncio.wait_for() that now waits until the cancellation is complete, or asyncio.all_tasks() returning only pending tasks. A lot of little things that add up.
The whole ergonomics are better, up to the command line experience with "python -X dev" which automatically add warnings and set asyncio in debug mode, and frankly you can't cleanly code async without.
The final nail in the coffin are the context vars (https://docs.python.org/3/library/contextvars.html). It's the only sane way to deal with a global registery that is dependant of the current running task.
It's almost always easier to upgrade to 3.7 than trying to use asyncio before it.
The idioms and programming styles change over time. Languages age. You add more syntax and semantics until some people start preferring more simple solutions and everything starts again.
C has stayed clean but C++ can be seen as fork of C into never ending complexity.
Java started as small language intended to be used like Javascript.
JavaScript started as small, now it's becoming Java.
I mostly still use the same features I used 10 years ago. And so do most of my clients.
But occasionally, I have the option to go the extra mile, and use asyncio for perfs or type hints for robustness.
The language grew big, but you don't feel it on the day to day coding.
Like Lua did. Like Rust did.
Imagine this:
def foo():
return "bar"
async def foo():
return "bar"
How do you know how to call that function? It's called the same thing. It has the same signature.. It returns the same thing. One is sync, the other is async. This is "colored functions".You have to call the 2nd one like:
await foo()
why do you have to care about that? It's either a coroutine or it's not. All functions in Python should just be callable like normal functions. But the Computer Scientists went and messed that up and made colored functions.It's absurd.
What I mind is having to do "async def", "async for", "async with" all over the place for no good reason. Python didn't do that with generators; you defined an ordinary function, and if it had a "yield" somewhere in its body, it returned a generator. I don't have to do "gen def", "gen with", "gen for", etc. to remind the interpreter that it's a generator.
The obvious way to handle async coroutines is the same: you define an ordinary function, and if it has "await" somewhere in its body, it's a coroutine. I shouldn't have to be reminding the interpreter everywhere that it's a coroutine.
(The reason "await" is a special case is that, with a generator, it's just an ordinary iterable, so it's not yielding control if I just use it like any other iterable, say in a for statement. If I want to do something with the generator that might yield control (as in the "using generators as coroutines" paradigm that came before async/await), I have to call its "send()" method, or otherwise do something special that will stand out. So there's no need to add a keyword for it. But with a coroutine, ordinary call sites that wouldn't yield control with any other kind of function can yield control, so it makes sense to add a keyword to make that explicit.)
gen def stuff()
Because it doesn't, people are very confused about generators, and think they are functions, which they are not. They are completely different objects.
Plus there is no way to tell if a definition is a generator without reading all of it.
Explicit is better than implicit and all that.
IMO `async for` and `async with` are misnomers - they are statements that call asynchronous functions (`__anext__`, `__aenter__` and `__aexit__`) so would have been better named something like `for await` and `with await`.
`async def`, on the other hand, was just copied cargo-cult-style from C#. I don't think it's necessarily bad, but you're right to say that it's inconsistent with Python's existing generators.
The reason there's a difference between foo() and await foo() is that the former gives you a future (aka Promise in JavaScript), while the latter gives you the result. You can then wait on multiple futures, so that things can happen concurrently.
If you add type annotations to your code and use mypy (which you definitely should), it'll pick up the distinction between the two types - Awaitable[str] vs str - and give you an error if you try to pass the future object to a function that expects a string.
The only case where I've run into problems is where I've called an async function that returns None, but have forgotten to await the result. In that case the function never actually begins execution.
x = get_something_from_global_state()
y = foo()
insert_into_global_state(x, y)
If the program is suddenly possibly concurrent when calling foo(), then perhaps x is no longer valid. Good luck debugging that. await foo() makes it much more obvious.Now, of course, in scenarios where you don't really care about this property, e.g. if you're dealing with a database in another process where it is obvious that stuff may happen behind your back, or if you don't actually have any concurrency, I get that await is probably pretty annoying.
In fact I'm pretty sure generators and async/await are almost the same feature, with possibly just some additional logic to allow await to suspend computation (so you don't have to write a loop `while not done(): sleep()` manually).
async def foo() is not a function and it doesn't have the same signature: the async is very explicit.
It's a different primitive, and it's not used AT ALL for the same thing at a function.
It's like writting:
def foo():
yield "bar"
and saying, 'how do you cal that function? How do you know how to call that function? It's called the same thing. It has the same signature.. It returns the same thing. One has one exit point, the other has several. This is "colored functions".You have to call the 2nd one like:
next(iter(foo()))
It's absurd'Well, no, it's not. It's a different tool. It's not a function, it's a generator.
You don't have to care about async/await. In fact, you can live your entire life without using them.
But it's a handy tool that allows you do:
- delegate asynchronous behavior, like I/O, outside of your callable
- make you match the syntaxic order with execution order despite said delegation
- make it clear and explicit where you chose to do so, indentifying the context switching of your program
Does it seems complicated ? It's because it is, and you probably don't need it.
But if you need it, it's easier than the alternative of using callbacks, and less error prones that implicit asyncronicity.
With Lua’s stackful coroutines, this information would either be hidden or just a naming convention, e.g. read_file vs read_file_async.
async def
is terrible, of the syntactic/semantic options it is the worst.
Best would have been to just allow creation of a name of a coroutine-usable version of a function-
def f: # normal f ....
a = async(f)
That allows existing functions to be turned into coroutines while not introducing the new syntactic pattern of a double word declaration.
If you’re arguing for generator-based coroutines, then (1) that’s not just any normal function (check inspect.isgeneratorfunction and inspect.iscoroutinefunction); (2) it was already explored and deprecated. Guess we can have another talk on why if you wish.
I have had the pleasure of engaging with cooperative vs scheduled concurrency since the 1980s, in the early days of the Mac, and asynchronous IO since it started to enter the mainstream in the 1990s. I don't write enough python any more that this impacts me much; more that I remember finding out about it and being astonished.
That's not to say- the async PEP is well written and one gets the mental model the author is promoting and the problems the PEP is trying to solve. I used tornado a bunch in its early days and it was and I'm sure still is a lovely piece of engineering.
Nevertheless, among the reasons for my astonishment were:
* there is a difference between cooperative concurrency and largely IO-scheduling driven asynchrony. There are a range of protocols that callers and callees engage in, a level of greater or lesser interest that the caller has on what and when the callee does it, and a variety of ways the callee can make what it did more or less eventually known to the caller. Cooperation and async capture two distinct common use cases in this rich space, yet the python implementation seems to improperly lump the two together. And the added keywords are crude and only provide partial expression of the range of options. For instance, deadlines are a top level consideration both in cooperation and in asynchrony, yet there is no syntax for specifying them.
* there is a level of sophistication required for effective cooperative or asynchronous programming that, despite the rise of node and so forth, is simply not met by the bulk of programmers employing it, nor necessary in the programs they are writing. Elevating the syntax to first class as though it is something for most python programmers to consider- well, you can have a synchronous function, or an asynchronous function, pick one- is putting power tools in the hands of people who mostly don't know how to use them working on problems that entirely don't need them. Especially for python, this seems like the wrong thing to have done.
* the doubled keywords pattern is ugly. Yes, if you are going to allow for cooperative behavior, decorating the affected syntactic entities is necessary. If it had to get added to the language I would much rather have seen new single tokens- adef and afor- for this purpose, maybe added to an "expert" module to be "imported" before use. With a whole new declarative keyword, one asks- what else can this be applied to? Why not have async variables or instance members? The syntax suggests itself and there are potential semantics.
Forgive me, but I was shocked when I saw this and still think it was an immature and unnecessary addition to the language.
for example
@asyncio.coroutine
def hello():
return "foo"
Although not for long, they deprecated it in 3.8 and will be removed in 3.10. I wish they would leave it, since I was able to use them to write API that could be synchronous or not depending which constructor was invoked. I'm wondering if there are better ways to do it.What is an example of being more incomprehensible?
>Python code doesn't even work with Python code
Is this statement a function of the 2 > 3 transition.
Migrating away from the pseudocodeness of Python.
Just a guess though I have about the same experience as you.
Python's type hints, in particular, have added a huge amount of complexity to the last few versions of the language.
However, the numerous (very long) typing-related PEPs are definitely making the language larger and more complex.
Also, any code that uses annotations is more verbose and less like what I want from Python - executable pseudocode.