How do you use decorators in Python?
Decorators are tools in Python for extending function behavior. 1. The decorator is essentially a callable object that receives a function as a parameter and returns the wrapped function; 2. Use the @decorator_name syntax to apply the decorator, such as @logger or @repeat(3); 3. Common uses include logging, permission control, cache and routing binding (such as the Flask framework); 4. Notes include correctly returning the wrapper function, using functools.wraps to retain metadata, and the execution order of multiple decorators is nested from bottom to top.
Using decorators in Python can feel a bit confusing at first, but once you get the idea, they're a powerful way to modify or enhance functions without changing their actual code. At their core, decorators are just functions (or classes) that wrap another function to add functionality.

What Exactly Is a Decorator?
In simple terms, a decorator is a callable (like a function or class) that takes another function as an argument and extends its behavior without explicitly modifying it.
For example, imagine you want to log when certain functions are called. Instead of adding print statements inside each function, you can create a @logger
decorator and put it above any function you want to track.

Here's a basic structure:
def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") Return wrapper @my_decorator def says_hello(): print("Hello") say_hello()
This will output:

Before function call Hello After function call
How to Create and Use Your Own Decorator
Creating your own decorator usually involves nesting functions. Here's how to do it step by step:
- Start with a function that takes another function (
func
) as an argument. - Define a wrapper function inside it that does something before and/or after calling
func
. - Return the wrapper function from the outer function.
- Apply the decorator using the
@decorator_name
syntax right above the target function.
If your decorated function needs to accept arguments, use *args
and **kwargs
in the wrapper so it can handle any number of positional and keyword arguments.
Example:
def repeat(num_times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(num_times): result = func(*args, **kwargs) return result Return wrapper Return decorator @repeat(3) def greet(name): print(f"Hello {name}") greet("Alice")
This will print "Hello Alice" three times.
Common Uses for Decorators
You'll often see decorators used in these common scenarios:
- ? Adding logging, timing, or access control to functions
- ? Implementing authentication or permissions in web frameworks like Flask or Django
- ? Caching results (eg, using
@lru_cache
) - ? Converting functions into properties (
@property
) or static methods (@staticmethod
)
These uses help keep your code clean and reusable. For instance, in Flask:
@app.route('/home') def home(): return "Welcome!"
The @app.route()
decorator connects the URL /home
to the home()
function.
A Few Things to Watch Out For
Decorators are super useful, but there are some gotchas:
- ✅ Always remember to return the wrapper function inside your decorator — not call it.
- ❗ If you don't use
functools.wraps
, the metadata (like.__name__
) of the original function might be lost. - ⚠️ Order matters when stacking multiple decorators — they run from bottom to top.
So this:
@decorator1 @decorator2 def func(): pass
Is equivalent to:
decorator1(decorator2(func))
Also, if you're debugging, it can be surprised to see a decorated function reporting the name of the wrapper unless you use @functools.wraps
.
Basically that's it. Once you understand the pattern — wrapping functions to extend behavior — you can start building your own or reading others' more easily.
The above is the detailed content of How do you use decorators in Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

Use httpx.AsyncClient to efficiently initiate asynchronous HTTP requests. 1. Basic GET requests manage clients through asyncwith and use awaitclient.get to initiate non-blocking requests; 2. Combining asyncio.gather to combine with asyncio.gather can significantly improve performance, and the total time is equal to the slowest request; 3. Support custom headers, authentication, base_url and timeout settings; 4. Can send POST requests and carry JSON data; 5. Pay attention to avoid mixing synchronous asynchronous code. Proxy support needs to pay attention to back-end compatibility, which is suitable for crawlers or API aggregation and other scenarios.

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True
