Advanced Python Features
1. Typing Overloads
In Python, @overload tells the type checker to expect different signatures for the same function. It doesn’t actually define multiple versions of the function itself, unlike Java or C++.
from typing import overload
@overload
def get_user(id: int = ..., username: None = None) -> User:
...
@overload
def get_user(id: None = None, username: str = ...) -> User:
...
def get_user(id: int | None = None, username: str | None = None) -> User:
...
2. Keyward-only & Positional-only Arguments
def foo(a, b, /, c, d, *, e, f):
...
5. Protocol
from typing import Protocol
# Add the @runtime_checkable decorator if you want isinstance() checks to work
# alongside your Protocols!
@runtime_checkable
class Quackable(Protocol):
def quack(self) -> None:
... # The ellipsis indicates this is just a method signature
class Duck:
def quack(self): print('Quack!')
class Dog:
def bark(self): print('Woof!')
def run_quack(obj: Quackable):
obj.quack()
run_quack(Duck()) # Works!
run_quack(Dog()) # Fails during TYPE CHECKING (and runtime)
6. Context Managers
# NEW SYNTAX - New contextlib-based context manager
import contextlib
@contextlib.contextmanager
def retry():
print("Entering Context")
yield
print("Exiting Context")
9.2 Walrus Operator
if response := pattern.search(line):
print('You pressed:', response)
else:
print('You pressed nothing')
Published: 2025-06-11