Advanced Language Features
Prerequisites: Functions, Classes and objects
A few features that show up constantly in real Python codebases once past the basics:
# Decorators: wrap a function to add behavior around it
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
add(2, 3) # prints "Calling add", then returns 5
# Context managers: the "with" statement's underlying protocol
class Timer:
def __enter__(self):
print("Started")
return self
def __exit__(self, *args):
print("Stopped")
with Timer():
print("Working...")
@log_calls is Python's decorator syntax — shorthand for
add = log_calls(add). Any class implementing __enter__/__exit__
can be used with with, the same protocol open() uses under the hood.