Meaning
A decorator is a function that modifies the behavior of another function or class without permanently changing its source code. It addresses the pain point of code duplication when applying the same cross-cutting concerns (like logging, timing, or access control) to multiple functions. It is triggered when developers need to add functionality to existing functions in a clean, reusable way.
Primary Function
Metaprogramming
Communicative Purpose
Enables adding functionality to functions or classes without modifying their core logic
Pattern
@decorator_name def function_name(parameters): # function body pass
Core Structure
@... def ...(...): ...
Função primária
Metaprogramming
Propósito comunicativo
Enables adding functionality to functions or classes without modifying their core logic
Situações de gatilho
Web development: adding authentication checks to multiple view functions Data science: caching expensive function results with memoization Systems code: measuring execution time of performance-critical functions
Contextos
Python web frameworks (Django, Flask), data processing libraries, and any Python codebase using aspect-oriented programming patterns
Padrão
@decorator_name def function_name(parameters): # function body pass
Estrutura central
@... def ...(...): ...
Slots de substituição
decorator_name: name of a decorator function, function_name: name of the decorated function, parameters: function parameters
Colocados típicos
- functools.wraps
- property decorator
- classmethod decorator
- staticmethod decorator
Substituições comuns
- Using inheritance or composition instead of decorators (more verbose but explicit)
- using metaclasses (more powerful but complex)
Erros comuns
Forgetting to return the wrapper function in a decorator (causes None return), leading to broken function calls Not using functools.wraps (causes loss of original function metadata like __name__ and __doc__), breaking introspection Applying decorators in the wrong order (order matters as they nest from bottom to top), causing unexpected behavior
Similar / contraste
Metaclasses: modify class creation rather than function behavior Context managers: handle resource setup/teardown (using 'with' statement) rather than function wrapping Inheritance: achieves code reuse through class hierarchies rather than function wrapping
Interferências
Coming from Java: may use annotations similarly, but Python decorators are functions that execute at import time, not just metadata Coming from C#: may expect attributes to be compile-time only, but Python decorators run at runtime and can modify behavior dynamically
Família do chunk
- @property
- @staticmethod
- @classmethod
- context manager protocol
Nuance
Do not use decorators for simple function modifications that could be done with direct function calls (over-engineering) Decorators add slight runtime overhead due to extra function calls; avoid in tight loops where performance is critical Class decorators modify the entire class and must return a class object, unlike function decorators which return a function
Efeito pragmático
Promotes code reuse and separation of concerns by isolating cross-cutting logic, making core business logic cleaner and more maintainable
Dica de memória
Think of a decorator like a gift wrapper: you take a present (function), wrap it with decorative paper (decorator logic), and the wrapped present still functions as a gift but now has extra appearance/behavior
Nota
The @ symbol is syntactic sugar for calling the decorator function with the target function as argument: @decorator is equivalent to function = decorator(function)
Upgrade path
@property, @staticmethod, @classmethod
Log in to save chunks.