Python Decorators
Decorators are a way to change, enhance or alter in any way how a function works.
Decorators are defined with the @
symbol followed by the decorator name, just before the function definition.
Example:
@logtime
def hello():
print('hello!')
This hello
function has the logtime
decorator assigned.
Whenever we call hello()
, the decorator is going to be called.
A decorator is a function that takes a function as a parameter, wraps the function in an inner function that performs the job it has to do, and returns that inner function. In other words:
def logtime(func):
def wrapper():
# do something before
val = func()
# do something after
return val
return wrapper
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025