xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Decorators

More Python10 min readLesson 3 of 7

3.1 A function that takes a function

Functions are values in Python, so a wrapper function can accept another function, define an inner function, and return it. The @decorator syntax is shorthand: the name below is replaced by the decorated version.

Always copy the wrapped function's metadata with functools.wraps. Without it, the decorated function keeps the wrapper's name and docstring, which confuses tracebacks, documentation and tools that inspect signatures.

python
from functools import wraps

def log_calls(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        print("calling", function.__name__)
        return function(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    return a + b

print(add(2, 3))

Output

calling add
5

Decorators are common for logging, timing, retries, permissions and caching (functools.lru_cache). Keep them small and preserve the signature with *args, **kwargs so the wrapper works for any function.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01Why does the decorated function lose its name?

    The wrapper replaces the original function. functools.wraps copies the name, docstring and other metadata back onto it.

  • 02Can I stack decorators?

    Yes. The one closest to the function is applied first, and each layer wraps the previous result.