by salmo · 4y ago · 0 comments
I liked f-strings. Asyncio has its place but is waaay overused. Typing was a cool idea, but so awkward in practice.
All of it has really turned me off, personally. It’s getting to where reading libraries is just painful. The simplicity of the language was really beautiful and when I wanted type safety, etc. I’d use something else. I can still write simple Python, but it’s more all the other code I need to grok.
I find myself going to Go more and more for stuff I used to use Python for. It’s easier to set up a dev environment for other people, easier to distribute code, and gives me type safety and concurrency as first class citizens while being a very small language.
I miss dictionary comprehensions and other shortcuts from time to time. But it actually feels more ergonomic now.
All personal opinion. I’m fine shifting languages. I still write C from time to time to bang bits. I play with various LISPs to exercise my brain. I never used Python for performance critical code. I guess ML is changing that need.
But I know others that want Java to have functional features and Python to have this stuff.
I’m not saying I’m “right”, just uncomfortable in a place I used to love to hang out in.
I'm very happy python survived the 2-to-3 migration and is now thriving more than ever! Looking forward to the 3.11 speed improvements.
Go and Python code may have significant difference. But there is spiritual overlap in the sense that Go really encourages a straightforward imperative programming style, which makes its code more accessible to a wider range of developers.
The Go fans keep insisting that this error handling in Go is new and fresh. I looked at my Go code, I saw that 2/3 of it is basically checking if a function returned an error, and I moved on. I've done it this way - I am not going there again.
And no, it doesn't force you to handle errors. You can simply not check for errors, just as you would swallow an exception.
My impression of the Go culture is that of the hip kids discovering vinyl.
As my former boss used to say - "there is an easy way, and there is the cool way".
As an anecdotal data point... I like Python and prefer it to Go for the most part. However, in the case of error handling, Go seems to get it right and Python does it very wrong. Exceptions are extremely confusing, I just can't wrap my head around them. I don't even accept, philosophically speaking, the concept of exception: there are no "exceptions" when running a program, only conditions that you dislike.
My example of error handling done right would be Rust's `Result<T, E>`. There's the ? operator for syntactic sugar to propagate errors upwards. Otherwise, to skip error handling, you're generally forced to unwrap() the result, which is a noticeable smell, and it will crash your program if the operation failed (as opposed to continuing despite the error). Finally, it maintains the error code advantage of keeping the control flow explicit and visible.
We've had decades of erroneous error handling from C codebases to learn from. Frankly, it's insane that we have a modern language that still uses error codes in essentially the same way.
Python style exceptions, pros:
- rapidly drop through layers when needed to get to a stable entry point - easy to add errors deep in the stack
Cons:
- basically a limited GOTO, therefore side-effect, therefore not composable - no way to know if what you are calling is gonna throw on you
Java pros:
- have to declare exception types, so at least you know what you are dealing with
Cons:
- you have to always declare exception types, which can be tedious - same non-composable GOTO-lite behavior - adding an exception deep in the stack is tricky
Go pros:
- errors are values, therefore typed and technically composable - no surprises
Cons:
- tedious, verbose - can't rapidly unwind unless you panic - rarely composable in practice, requires manual unwrapping in most cases - adding an exception deep in the stack is tricky
Rust Result pros:
- strongly, statically typed - no surprises - higly composable - can map over it - rapidly unwind in a composable way with ? operator
Cons:
- adding an exception deep in the stack is tricky (but often amenable to programmatic refactoring)
It's no wonder Rust is the SO most loved language 7 years running.
Python actually has a Result type library which I really like, but it's been hard selling my team, and you really need buy in. But I'd give it a swing.
Master Gorad asks his apprentice:
"How many statements does it take to call a function in Go ?
Apprentice replies puzzled "I can just call foo();" and I am done ?
Master Gorad beats his student with a cane. No, you silly, it takes at-least 3 statements to make a function call in Go:
r, err := foo();
if err != nil {
return nil, err;
}But the flipside is that encoding every failure condition in the type system quickly becomes unfeasible. Every allocation can fail. Every array/slice indexing can be out of bounds. Some errors might just not be recoverable at all while maintaining consistent state. Go has the null pointer problem...
That's why both Go and Rust hide certain error conditions and have a fallback mechanism (panic/recover).
There is a balance between the two idioms, and which one is right depends on the language and the facilities the type system provides.
Interesting. For me it's very much the opposite. What about them do you find confusing?
> I don't even accept, philosophically speaking, the concept of exception: there are no "exceptions" when running a program [...]
I think you're looking at it wrong. Exceptions, as implemented in the languages I know, are more about having a framework of allowing inner/library code to drop the ball and run away screaming, without making more of a mess.
It also allows the calling function to ignore the mess and hope that something further up the call-chain will deal with it.
Exceptions circumvent the normal control-flow of a program, and that makes code less obvious to follow. When I see foo calling bar() in go, I know where, and if, errors returned by the function are being handled, just by looking at foo.
When I see foo calling bar() in Python, and there is no try-except block in foo, I have no idea what happens to any errors that bar may return. I now have to check everyting that calls foo, which may be multiple other places, each of which could have a different Exception handling, or none, in which case I have to also check all the callers of that caller of foo, etc.
And even if there is a try-except, I have to check whether except catches the correct TYPE, so now I also need to be aware of the different types of Exceptions bar may raise ... which in turn depends on everything that bar calls, and how bar itself handles these calls, etc.
Yes, error handling in Go is verbose. Yes, it would be nice if it offeres a little syntactic sugar to improve that.
But error handling in Go is also obvious.
They are non-local jumps. They make reasoning about the code very difficult. When you read code, you have to treat all conditions symmetrically and equally likely (e.g., whether a file exists or it doesn't). Using exceptions for control flow, as is done sometimes in python, forces an unnatural asymmetry between cases that I find confusing. And this is just when there is a single exception at stake. Typically, several exceptions fly invisibly over the same code and it becomes impossible to understand (unless you assume that no exceptions occur, which is the wrong stance to take when analyzing an exception-riddled code).
TL;DR: raise and except are a corporate-friendly renaming of goto [0] and comefrom [1].
But our vocabulary is full of such things. A "method" is not a particularly descriptive term given what we use it for these days, either. At the end of the day, so long as everybody knows what it is, it's not a big deal.
Conceptually, though, it can be treated as an error monad.
Exceptions are very much not a monad, that's one of the biggest pain points about them. You can't map over exceptions. They are a control flow statement.
If you're not familiar with algebraic data types, they're well worth learning about, and not a difficult concept. Once you use a language with them, heading back to a language without them feels like developing with one hand tied behind your back.
Exceptions, aka faults, are a time-tested feature of CPUs that have been around for half a century:
Since messages in this channel propagates up the call stacks they are very handy to stop an application and therefore used for error handling.
But they can just as well be used for all sorts of other messaging. In base Python they are used to communicate that you’ve reached the end of an iteration.
If you’ve ever made a function that returns both a value and a status in as a tuple, chances are you are better off using exceptions to communicate the status, especially if there is a “stop” status.
Golang actually has a back-channel communication path that is somewhat similar as a second channel of communications. (Actually they're called channels!) They're a first-class and extremely powerful feature of the language. You can even run a for loop over them, block or not block while waiting for an incoming message, etc.
Here's a great video that talks about use cases and the patterns in using them, and they pair great with goroutines (and you don't have to sprinkle async before every function, either): https://www.youtube.com/watch?v=f6kdp27TYZs
I work in both Python and Go. I love both languages. Here are a few reasons why I chose Go over Python for a lot of things these days:
Alot faster, self-contained executables instead of virtualenv, scales natively, no GIL, linear code in goroutines instead of asyncio.
This really is the only practical area where Go is superior to Python. No messing with 3rd-party libs, no compromises, no hacks... Everything else is not really critical for most people, and largely not worth losing all the nicer features of Python for; if they could just fix it once and for all in stdlib, just blessing one compilation format and making it well-supported on all the big platforms, it would be a big step forward for the ecosystem.
Easier said that done, of course.
Especially considered the obligatory compilation step and lack of IPython.
And while there it certainly does provide a lot of benefits, it does make the language look more and more like a huge pile of patchwork and afterthoughts. It neither feels simple nor consistent and the tooling is a mess as well, both overly complex (e.g. half a dozens tools to do basic type checking) and lacking really basic important features (e.g. easy way to compile ship able binaries).
Especially after all the pain of the python3 transition, it feels just frustrating how much of a mess it all is. The "only one way to do it" philosophy seems to have been thrown overboard a long while ago.
That's impossible, because it's not a type system at all.
It's type hinting, effectively a documentation feature, and sure, you can misdocument stuff. If people started building tools that rely on it to hack an actual type system on top of it, well, it's their problem. Duck typing is not affected by it in any way.
Well, yeah, because that's a compile-time check, not a runtime check. Use Pydantic if you want runtime validations.
> The new type system goes pretty much against the idea of duck typing,
It's very much orthogonal, due to the aforementioned distinction. Type annotations are compile-time. Duck-typing is run-time. You can still type-hint something and then call an attribute that isn't on the interface, and you can suppress the type error with `# type: ignore`. But also, if you know you are using quack(), you probably want foo(duck: Duck).
How so? Python’s Protocol and TypedDict have their limitations but are structurally typed.
> `a: int = "foo"` goes through the python interpreter without even a warning
As long as you’re validating inputs then you don’t need type validation at runtime. Input validation ensures that static types are representative of runtime types
> As long as you’re validating inputs then you don’t need type validation at runtime.
The issue is that type validation is done by a different tool, that follow similar, but not identical rules to the runtime. So it's very easy to create code that passes the type checker, but fails at runtime or vice versa. Type validation is something Python should be able to do itself, it's part of the language after all.
This typing annotation system is just as half-baked as Python's class system. No, having syntax sugar for instancing "objects" that amount to new dictionaries is not an alternative to proper OOP.
And even having a "proper OOP system" means little when you have to dig knee deep in class hiararchy. Source: just had to debug a Java application today. Not my idea of fun.
Sometimes, planning stuff from the ground-up goes a long way to reducing future "code debt". Otherwise, leaving it at basics is sound enough.
Type annotations, imho, are actually useful and not really hard to read.
Walrus is...fine. I don't use it much, but I defo see how it's one more thing.
Python's biggest complexity, imho, is its almost unrivaled dynamicism. There's just too many degrees of freedom at times.
The import system continues to be a nuclear footgun. I consider myself a python expert with 15 years under my belt and today I was still fighting with imports in a pytest suite. Like wtf.
I want to be able to use typing everywhere if I'm going to use it, it really grinds when I have to selectively not use it.
That being said, im glad typing is in the language :)
What this means is I can import my AppConfig class anywhere (except types and config submodules) without circular imports, construct them, and they will be initialized with the configs from the env.
Occasionally I have to bust out ForwardRef annotations and model.update_forward_refs() but that's pretty rare. Basically, the imports are structured so that it's as close to a DAG as possible.
Definitely check out pydantic, it makes it really easy to do 12-factor style application config.
I haven't done a lot with CLI-flag global config, but if I had to, I'd use something like dependency-injectors to wire it all together.
FYI: You can use strings as a workaround, or the
from __future__ import annotations
trick.Do you keep the value on the left, the value on the right, error out, try merging the values (if so: how?), add a parameter allowing the user to make that choice, require the user to pass a lambda?
I don’t think there’s a ‘best’ answer here, but if you want to make one of them easier to write as a|b, you can only support one.
>>> {1} | {1.0} | {True}
{1}
But the behavior for dicts is surprising even in that light: >>> {1: 1} | {1.0: 1.0} | {True: True}
{1: True}I’d be cool with a statically typed flavor that wouldn’t allow for the type gymnastics.
But that’s gross with the None situation where you’d have to fall back to magic values vs ‘nil’ or similar concepts. None was one of my favorite things back when other languages didn’t address it.
And a lot of my opinion is probably based on the fact that I came to the language in the late 90s from a Pascal/C background. Probably just getting to old :).
In the end, I'm glad that Python is changing to meet the changing developer zeitgeist, even if I might have to play catch up with new features sometimes. It means Python will stick around and won't be considered "old and outdated" and fall out of use because it failed to keep up with what the developer community wants and expects. It's also the same reason why I'm glad that Go got generics.
I love stuff like 'match', the walrus operator, Typing, etc. but it definitely feels like a lot to grok and it will be increasingly hard for new programmers to read arbitrary python code without grokking all of the new stuff.
PHP has a long history of doing things in a "right way" that subscribes to copying whatever one language is doing for 5 years. It first did things the C way, then the Java way, then got inspired by Ruby and Javascript, etc. The features are there, but executed in very awkward ways.
Ruby as a language explicitly blesses many ways to do the same thing.
Every new release in C# seems to bring in as many features as you'd get in 4 or 5 major Python or Java releases.
I look at the Python I wrote 8 years ago and it's _fine_. Even Python 2.6 code written with large frameworks looks similar enough to modern Python. The same can't be said for Javascript, Java (Java's best practices have changed a lot since then), C++, or C#.
Yes, but people have been attracted to Python largely because it's not like a lot of other languages. It is/was concise, simple, dynamic and fairly easy to learn. I think some of the new features, even if they don't make it a worse language, make it less "Pythonic", and so tend to undermine its comparative advantage. For experienced programmers the new features might not seem complicated, but python is used by a lot of people who are not in that category, including people for whom software development isn't their primary job.
Try using a walrus operator in a multi-line if/elif statement or a complex comprehension.
Try to understand the subtleties of the new dictionary merge operator.
And the best one, try learning the typing annotations.
All this on top of already complex OOP class system.
Good luck.
But then yea, 1 line of python using an inbuilt function solves a 10 line go routine in a hackerrank.
Second: it's not a good function to use. Checking if something is present in an array is not something you should do often and thoughtlessly. It has its uses, I agree, but in general a "dict", or if you really need an array, binary search, should be used. Where's the one liner for that in python? O wait, there isn't one. Go does have it, though, since a long time.
But it's a good thing we no longer use LoC as a measure.
Here it is:
>>> import bisect
>>> sorted_fruits = ['apple', 'banana', 'orange', 'plum']
>>> bisect.bisect_left(sorted_fruits, 'banana')
1For dict/set hash lookup, O(1):
x in s
For binary search on a sorted python list, it takes a standard library import (bisect), and the containment test is: (i:=bisect.bisect_left(a, x)) < len(a) and a[i] == xSo, yes, let's have a contains function on (unsorted) arrays.
And, contains is a perfectly cromulent function to use unless there's a reason not to. At a million items it would be a bad use of contains if you were to lookup up multiple items, but modern day programming requires both knowledge of the code structure and the data.
Yes, python's type hinting is pants.
Go's goals are simplicity, python wants to be the working man's language.
print("quux" in {"foo", "bar", "baz"})Go made multiple decisions that make me face palm. It was so close to being a great systems programming alternative.
A pythonic C++ that doesn’t smell bad.
I wish Go had classes. I like those damn things. Extending a Dog from Animal with all the methods and data in one place is nice.
Closer to 50.
The fact that simple reusable utility functions were/are complicated does make it feel half baked to me too.
I'm not sure I get this. Asyncio is a serious commitment. You don't really want it unless you really want it. And even then in the libraries you may want both the sync and async path. I feel like most asyncio libraries would just not exist without it - so if you're not interested in that area, can't you ignore them?
Most people thought otherwise, because they don't bother to read the reference manuals.
Which is why making an already complex language even more difficult a very big mistake.
Python has a lot of things in the standard library, though I think the tendancy has been to stop adding things (case in point: I believe there is very little argument against putting requests into the standard library. I get why they don't but I disagree with the reasoning)
Yep you're right, there's even an official effort to clear some of these out: https://peps.python.org/pep-0594/
These days Python is targeted towards general scripting, data processing, scientific computation, etc. It’s really good as a glue language or for anything involving numpy. I use Python every day but I would not use it to build applications.
A billion requests per month is 400 requests per second. My toaster can do better than that :)
Not to say that your product isn’t capable for many use cases, but the fact that the 1krps range is something impressive in Python world is indicative of the issue: Python is not built for speed, it’s built for convenience, and increasingly it’s competing against more modern languages that offer both.
[0] https://star-history.com/#tiangolo/fastapi&django/django&pal...
I don't see it that way. I see a rapidly growing library still in pre-1.0 and a BDFL trying to wade through a mountain of "contributions", a lot of them garbage, trying to keep code quality high in one of the most pristine and readable source code repos I've ever seen.
Also they have crowdsourced 17 languages for documentation translation. And it's up to date. That's bonkers. You're lucky if english documentation is accurate and up to date in many open source codebases.
Could you please elaborate?
It’s really only good for apps or things I (or other Python people) are going to run.
Part of it is that I don’t do analytics work. Now that PERL is niche, my use cases are no longer the target.
Can't you still use all those old features just as you did before? If you don't like the complexity of newer libraries and features, they're still optional aren't they?
Or did something fundamental shift (aside from the obvious P2->P3 switch) that has made existing features harder to use?
Compared to C++, where you can do incredible zero-overhead magic with the type system; for example duck-typing, once The Way, is now an absolute nightmare in Python's type system. Python typing is little but baggage and warts unless you've drunk the cool-aid and then you're horrified that people like me haven't.
(and, all that said, I'm quite excited about py3.11, it's great on performance and ergonomics)
The history of Python means that coders make functions whose return is usually quite clear, but when it's not, I'm really glad I have typing.
Also, some libraries like Pydantic make use of types in a very clever and productive way.
Really cool for parts of your code in which runtime type enforcing is important (eg. external interfaces)
Chances are you're not programming in a vacuum. These features will be used by third party libraries and you will have to read/understand this code.
Even in your in house codebase, there will always be co-workers that want to use these features.
The optionality of language features is not real. If they exist, they will be used, you will have to understand them, they will leak from other libraries, etc.
A lot of these issues just aren’t there in C++, and you probably wouldn’t even try to share a codebase for something with someone who’s not another expert. …and you’re most likely working on something big.
The big thing that’s plagued Python since 3.x is the distribution problem. You can’t just hand someone a script and maybe another one to user-install some requirements. You need to BYO Python, dependencies, etc.
Things like types, library management, etc. are being handled by external tools. If I want to onboard someone to collaborate with me they really have to have my version of Python (so probably pyenv), Pipenv or Poetry, mypy or whatever, pytest or whatever, black, and have the same config for some of them.
The verbosity overhead of Go (or Nim, etc.) is worth the trade off to me for most of my uses of Python. I can just hand someone a binary and the dev just needs the language installed and maybe like goimports.
I’ve never been married to one language. I like to use them for their wheelhouse. I’ll still use Python for 1-offs or some things I can ship in a container, etc. that I’m only working by myself or with experienced Python people on.
A lot of this is that it’s really turning into more of an Analytics language. The output isn’t expected to be shared and everyone around you is a Python dev.
And I’m old. I started when Python was so pretty to my Pascal/C self compared to PERL (shudder). The documentation is still amazing for the language and standard library. (No Google, I want the actual docs.) And you could onboard almost anyone to work on it if they had any programming background because it was such a simple language.
The 2->3 shift was really only bad for complex legacy codebases and when you primarily deal with bytes vs Unicode. The latter is really painful anywhere. It didn’t bother me much. I usually just had to fix a few small things or it gave me a good excuse to kill something that should have been retired anyway.
For the same reasons that you can't "just" use C++11 and ignore C++20.
The ecosystem moves forward, and you can't just sit behind no matter how much you would like to.
What I did want to mention was the improvements to the errors where you can see exactly what line, function call, etc., is causing the error will be a huge game changer in my opinion for the language and for adoption. It's ergonomic changes like that that make me bullish on the language going forward.
I’ve rewritten 3 CLIs because it’s too much of a pain for people to get them set up.
I still use it for myself to whip through a CSV, collate data from APIs. Sometimes a tiny API or web app (I really don’t like webdev) where I can deploy a container or pipeline deployment.
And I don’t have to use all the new bells and whistles. But so many do.
The type hinting system in particular is so much more painful to read (to me) than in a language with actual types.
> PyInstaller bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules. PyInstaller supports Python 3.7 and newer, and correctly bundles many major Python packages such as numpy, matplotlib, PyQt, wxPython, and others.
I’ll have to check it out.
Not specifically a new feature, but I remember wasting a good bit of time when coming across a line that was essentially:
return headers.get('x-foo') == settings.FOO_KEY is not None
and being extremely confused until discovering it was a use of comparison chaining[1] and was actually doing the right thing.[1] https://docs.python.org/3.10/reference/expressions.html#comp...
I'm a huge Python fanboy and this line is absolutely awful.
Comparison chains are great for stuff like "x < y < z" or "x == y == z", but the operators should never be mixed.
"Readability counts" is, IMO, the most important line in the Zen of Python, and that line is unreadable. I imagine it's equivalent to:
return headers.get('x-foo') == settings.FOO_KEY and settings.FOO_KEY is not None
Which, admittedly, feels like a clumsy line of code, but it's at least readable.