Advanced Python Features

(blog.edward-li.com)

Comments

edwardjxli 23 April 2025
Hey yall! Original author of the blog here!

I did not expect to wake up at 4am seeing my post on front page HN, but here we are nevertheless :D

As the intro mentioned, these started off as 14 small tweets I wrote a month prior to starting my blog. When I finally got that set up, I just thought, "hey, I just spent the better part of two weeks writing these nifty Python tricks, might as well reuse them as a fun first post!"

That's why the flow might seem a little weird (as some pointed out, proxy properties are not really a Python "feature" in of itself). They were just whatever I found cool that day. I tried to find something more esoteric if it was a Friday, and something useful if it was a Monday. I was also kinda improving the entire series as it was going on, so that was also a factor.

Same goes with the title. These were just 14 feature I found interesting while writing Python both professionally and as a hobby. Some people mentioned these are not very "advanced" per se, and fair enough. I think I spent a total of 5 second thinking of a title. Oh well!

robviren 23 April 2025
Every time I try to use Python I get this mixed feeling of liking how few guard rails there are between me and the logic I am making and this lingering worry that my code looks like fools attempt to use Python. So much exists as convention or loosely followed rules. Whenever I read articles like this I am wowed by the depth of things I didn't know about Python or how much has changed. It makes something like Go feel like a comfort blanket because I have reasonable certainty code I write won't feel deprecated or left behind a year or two later. Excellent article showing off even more I didn't know.
tzury 23 April 2025
My own opinion is that Python shall remain Python, and golang, Rust and Typescript each should be whichever they are with their unique philosophy and design.

I am coding in all 4, with some roughly 28 years now, and I don't like what is becoming of Python

There is a reason why python become that popular and widely adapted and used, and it is not the extra layers of type checking, annotations and the likes.

this looks familiar to me, but from other languages.

    response := get_user_input()

I am aware of the factI am in minority, and not trying to change anyone's mind, simply what this voice to be heard from time to time.

All in all, a very comprehensive list of some of the recent introduced features.

There is an older list on SO which readers might also find useful:

https://stackoverflow.com/questions/101268/hidden-features-o...

lyu07282 23 April 2025
Good list, its one of these things you either never heard of, or used for years and think everyone knew that. I'll add a few:

* did you know __init__.py is optional nowadays?

* you can do relative imports with things like "from ..other import foo"

* since 3.13 there is a @deprecated decorator that does what you think it does

* the new generics syntax also works on methods/functions: "def method[T](...)" very cool

* you can type kwargs with typeddicts and unpack: "def fn(*kwargs: Unpack[MyKwargs])"

* dataclasses (and pydantic) support immutable objects with: "class MyModel(BaseModel, frozen=True)" or "@dataclass(frozen=True)"

* class attributes on dataclasses, etc. can be defined with "MY_STATIC: ClassVar[int] = 42" this also supports abstract base classes (ABC)

* TypeVar supports binding to enforce subtypes: "TypeVar['T', bound=X]", and also a default since 3.13: "TypeVar['T', bound=X, default=int]"

* @overload is especially useful for get() methods to express that the return can't be none if the default isn't None

* instead of Union[a, b] or Optional[a] you can write "a | b" or "a | None" nowadays

* with match you can use assert_never() to ensure exhaustive matching in a "case _:" block

* typing has reveal_type() which lets mypy print the type it thinks something is

* typing's "Self" allows you to more properly annotate class method return types

* the time package has functions for monotonic clocks and others not just time()

anyone know more things?

globular-toast 23 April 2025
This is a nice list of "things you might not know" that is worth skimming to add to your toolkit.

If you are really interested in "advanced Python", though, I would recommend the book Fluent Python by Ramalho. I have the first edition which is still highly relevant, including the async bits (you just have to translate the coroutines into async syntax). There is a second edition which is more up to date.

I would also recommend checking out the functools[0] and itertools[1] modules in the standard library. Just go and read the docs on them top to bottom.

It's also worth reading the first few sections of Python Data Model[2] and then bookmarking this page.

[0] https://docs.python.org/3/library/functools.html

[1] https://docs.python.org/3/library/itertools.html

[2] https://docs.python.org/3/reference/datamodel.html

lordnacho 23 April 2025
For me, the biggest benefit to python is that it feels like executable pseudocode. The language gets out of the way of your domain level instructions. This is probably why most non-programmers have the easiest time with python.

The more fancy stuff you add to it, the less attractive it becomes. Sure, most of these things have some sort of use, but I reckon most people do not get deep enough into python to understand all these little things.

addoo 23 April 2025
The only things I’d have probably change about this list is the inclusion of some of the collections.abc containers for type annotations, TypedDict and how it can make working with strictly structured dictionaries not terrible (but if it looks like an class and quacks like a class, make it a class if you can), and Counter (only because I forget it exists every single time I should have used it).

Several comments disliking the walrus operator, like many of the features on this list I also hated it… until I found a good use for it. I almost exclusively write strictly typed Python these days (annotations… another feature I originally hated). The walrus operator makes code so much cleaner when you’re dealing with Optionals (or, a Union with None). This comes up a lot with regex patterns:

  if (match := pattern.search(line)) is not None:
    print(match.group())
Could you evaluate match on a separate line before the conditional? Sure. But I find this is a little clearer that the intended life of match is within the conditional, making it less tempting to reuse it elsewhere.

Not a Python feature specifically, but I’d also love to see code that uses regex patterns to embrace named capturing groups more often. .group(“prefix”) is a lot more readable than .group(1).

hiichbindermax 23 April 2025
Nitpick about 9.3 Short Circuit Evaluation: both things evaluate differently if you have empty strings. The if-else clause treats empty strings as valid while the or operator will treat them equivalent with None.
Loranubi 23 April 2025
I would argue that most of these features (basically everything except metaclasses) are not advanced features. These are simple, but for some reason less well known or less used features.

Metaclasses are however quite complex (or at least lead to complex behavior) and I mostly avoid them for this reason.

And 'Proxy Properties' are not really a feature at all. Just a specific usage of dunder methods.

lucideer 23 April 2025
As someone coming from Javascript/Typescript & now working full time in Python, this is a lovely - mostly fantastically useful - little resource. Some choice observations:

1. Typing overloads: TS has typed overloads I think largely as an affordance to an unfortunate feature of Javascript. In my experience overloads are an anti-pattern or at best code smell. It's nice that you can type them if you're cleaning up an existing codebase that uses them but I would consider them tech debt.

2. Keyword-only and Positional-only Arguments: This is the opposite of the 1st feature (ability to make method signatures more strict) but man is the syntax cryptically terse. I'd love to use this everywhere but I'd be concerned about readability.

3. Future Annotations: Thank you for this section - forward references have been a real pain for me recently & this is the first explanation that's scratches the service of the "why" (rather than just focusing on case-by-case solutions), which is much more helpful. Bring on PEP 649.

4. Generics: Cries in legacy 3.10 codebase

5. Protocols: As a Typescript guy, this seems very cosy & familiar. And not very Pythonic. I'm not sure how to feel.

14. Metaclasses:

> if you are that 1% which has a unique enough problem that only metaclasses can solve, they are a powerful tool that lets you tinker with the internals of the Python object system.

OR if you're one of the many devs that believes their problem is unique & special & loves to apply magical overengineered solutions to simple common problems, then the next person who inherits your code is going to really love your metaclasses. They sure make tracing codepaths fun.

djoldman 23 April 2025
This is wild and something I didn't know about:

https://blog.edward-li.com/tech/advanced-python-features/#2-...

   def bar(a, /, b):
       ...

   # == ALLOWED ==
   bar(1, 2)  # All positional
   bar(1, b=2)  # Half positional, half keyword

   # == NOT ALLOWED ==
   bar(a=1, b=2)  # Cannot use keyword for positional-only parameter
TekMol 23 April 2025
TFA's use-case for for/else does not convince me:

    for server in servers:
        if server.check_availability():
            primary_server = server  
            break
    else:
        primary_server = backup_server
    deploy_application(primary_server)
As it is shorter to do this:

    primary_server = backup_server
    for server in servers:
        if server.check_availability():
            primary_server = server  
            break
    deploy_application(primary_server)
William_BB 23 April 2025
I enjoyed reading the article. I'm far from a Python expert, but as an observation, most of these features are actually just typing module features. In particular, I wasn't sold on Generics or Protocols as I would have just used duck typing in both cases... Does modern, production-level python code use types everywhere? Is duck typing frowned upon?
davnn 23 April 2025
Working in the ML field, I can't hate Python. But the type system (pre-3.12, of course) cost me a lot of nerves. Hoping for a better post-3.12 experience once all libraries are usable in 3.12+. After that experience, I’ve come to truly appreciate TypeScript’s type system. Never thought I’d say that.
steinuil 23 April 2025
Turns out I managed to use almost all of these during a refactor of a project at work, even metaclasses... (Metaclass usage is justified in my case: we have a sort of language evaluator and using a metaclass lets us define function arguments with their types and validators in a very coincise and obvious way similar to Pydantic.)

I think this list should also include descriptors[0]: it's another metaprogramming feature that allows running code when accessing or setting class attributes similar to @property but more powerful. (edit: nvm, I saw that they are covered in the proxy properties section!)

I think the type system is quite good actually, even if you end up having to sidestep it when doing this kind of meta-programming. The errors I do get are generally the library's fault (old versions of SQLAlchemy make it impossible to assign types anywhere...) and there's a few gotchas (like mutable collections being invariant, so if you take a list as an argument you may have to type it as `Sequence[]` or you'll get type errors) but it's functional and makes the language usable for me.

I stopped using Ruby because upstream would not commit on type checking (yes I know you have a few choices if you want typing, but they're a bit too much overhead for what I usually use Ruby for, which is writing scripts), and I'm glad Python is committing here.

[0]: https://docs.python.org/3/howto/descriptor.html

pjmlp 23 April 2025
Here is another one, list and expression comprehensions shared with ML languages (not that AI one), apparently many aren't aware of them.

The itertools package.

krelian 23 April 2025
Python has evolved into quite a complex language considering the amount of features that come built-in. The documentation, while complete, does not facilitate discovery of many of those features.
stitched2gethr 23 April 2025
> @overload is a decorator from Python’s typing module that lets you define multiple signatures for the same function.

I'll be honest, I've never understood this language feature (it exists in several languages). Can someone honestly help me understand? When is a function with many potential signatures more clear than just having separate function names?

wismwasm 23 April 2025
Nice!

I would add assert_never to the pattern matching section for exhaustiveness checks: https://typing.python.org/en/latest/guides/unreachable.html#...

macleginn 23 April 2025
The way the language is evolving, it seems likely to me that people in the applications camp (ML, simple web-dev, etc.) will soon need a "simple Python" fork or at least an agreed-upon subset of the language that doesn't have most of these complications (f-strings are a major success, though).
smjburton 23 April 2025
Some of these newer features don't seem like improvements to the language (e.g. the Walrus operator):

'''

# ===== Don't write this =====

response = get_user_input()

if response:

    print('You pressed:', response)
else:

    print('You pressed nothing')
# ===== Write this instead =====

if response := get_user_input():

    print('You pressed:', response)
else:

    print('You pressed nothing')
'''

The first implementation is immediately clear, even if you're not familiar with Python syntax. If you don't know what the ":=" operator does, the code becomes less readable, and code clarity is traded away in favor of being slightly more concise.

hk1337 23 April 2025
I thought the typing overload was interesting because I thought it was going to be like overloading in C# and Java but it's really just useful for documentation and intellisense tools in IDEs.
mcdeltat 23 April 2025
Good article! I found the typing bits particularly interesting. This part of the language has been evolving rapidly recently, which is cool if you like static typing.

Although I think the example of type alises in section 4 is not quite right. NewType creates a new "subtype" which is not equivalent to the original type. That's different to TypeAlias, which simply assigns a name to an existing type. Hence NewType is still useful in Python 3.12+.

librasteve 24 April 2025
not sure whether to laugh or cry at this ... looks like over the years python has agglomerated some of the features raku has had from day 1 (2015) in sadly inconsistent ways, often via module includes:

  - multi subs & methods = "typing overloads"
  - named & positional args
  - stubs = "future annotations"
  - subsets = "Generics"
  - protocols
  - wrappers = "context managers"
  - given / when = "structural pattern matching"
  - my declaration = "walrus op"
  - short circuit evaluation
  - operator chaining
  - fmt
  - concurrency
 
If you are a Python coder and you feel the need for some of this, I humbly suggest you take a look at https://raku.org
mvATM99 23 April 2025
Good list. Some of these i knew already, but the typing overloading and keyword/positional-only arguments were new to me.

One personal favorite of mine is __all__ for use in __init__.py files. It specifies which items are imported whenever uses from x import *. Especially useful when you have other people working on your codebase with the tendency to always import everything, which is rarely a good idea.

nurettin 23 April 2025
My favorite hack is to use a single threaded ThreadPoolExecutor as my main thread. When another thread wants to communicate with it, it just queues the callback function into main using submit. This cleans up the architecture and avoids the use of Queue which is a bit slower.
red_admiral 23 April 2025
This sounds fun if you have 10x programmers or at least IQ > 140 programmers in charge. Last place I worked, I was told never use "smart" tricks if you can do the same thing in a simpler way. For-else and f-strings and := sound like harmless enough (though the last one is controversial); "with" is useful for resources that need to be deallocated but "yield"? Really? "more readable" when you slap a decorator on the thing? Why are we packing the enter and exit operations into a single function?

Playing with the typesystem and generics like this makes me worry I'm about to have a panic attack.

Give me code that I can understand and debug easily, even when I didn't write it; don't do implicit magical control flow changes unless you have a very good excuse, and then document both the how and the why - and you'll get a product that launches earlier and has fewer bugs.

Sometimes, a few more if statements here and there make code that is easier to understand, even if there's a clever hack that could cut a line or two here and there.

fxj 23 April 2025
This is all fun and games unless you have to debug someone elses code and they use a new feature that you didnt know about. Speaking for myself, I would be glad if there were a python_light version of the interpreter that has a simple syntax only like the early 3.x versions.

just my 2 ct

OutOfHere 25 April 2025
It is a great article, but it completely misses what's new in Python parallelism with the GIL being optional since 3.13, also multiple interpreters via InterpreterPoolExecutor coming in 3.14.
Starlevel004 23 April 2025
If context managers are considered advanced I despair at the code you're writing.
hrtk 23 April 2025
Trying so hard to make it a typed language
shaunpud 23 April 2025
Another blog with no feed :(
drumnerd 23 April 2025
Those are basic, you can decompile a function and change its bytecode, you can completely revamp the parser using codecs, etc