Search the courses, subjects, tracks, games and features, or jump straight to a page.
Learn it your way
A short class with Sarah and her students. The other ways are under More.
Sign up free to listen. Transcripts are free to read.
Today, we're going to learn about decorators in Python. Can anyone tell me what they think a decorator is?
Is it something that adds features to functions without changing their code?
Exactly! A decorator is a way to wrap a function to modify its behavior. It lets us 'decorate' a function with additional features.
So, like, if I wanted to log something every time a function runs, I could use a decorator?
Yes, that's a perfect example. You can create a logging decorator that automatically logs the function calls!
How do we actually code this decorator?
Let’s look at a simple example. Here's a function that adds logging to another function. Remember, a decorator is created using another function!
Now that we understand what decorators are, let’s discuss the @ syntax. Who can explain how we might implement this?
Is it like a shortcut for applying the decorator to a function?
"Correct! By using the @ symbol, we can apply a decorator in a very neat way. For instance:
Let’s explore practical applications of decorators. Can anyone think of an application?
I think logging is one! What about access control?
Absolutely! You can use decorators for logging, access control, and even for caching results. How might we create a logging decorator?
By defining a function that logs the input arguments and the results?
"Exactly! Here’s how it might look:
Let’s summarize what we learned about decorators. Can someone remind us what a decorator does?
It modifies a function's behavior without changing the code!
Yes! And what is the benefit of using the @ syntax?
It makes the code cleaner and easier to read.
Great! Remember, decorators serve various purposes, from logging to parameter management. Keep these concepts in mind!
Using a simple decorator to log execution:
def logger(func):
def wrapper():
print('Logging...')
func()
return wrapper
@logger
def say_hello():
print('Hello!')
say_hello()Wrapping a function with a decorator:
# This logger passes on the arguments and the return value, so it can wrap add(x, y)
def logger(func):
def wrapper(*args, **kwargs):
print('Logging...')
return func(*args, **kwargs)
return wrapper
@logger
def add(x, y):
return x + y
print(add(2, 3))Decorate your code with ease, modify functions, it’s a breeze!
Imagine a cake that you can always add frosting to without changing the cake itself; that's a decorator!
D.E.C.O.R.A.T.E. - Decorators Enhance Code Operations Regularly, Affecting The Execution.
D.E.C.O.R. - Decorators Enhance Code Operations Regularly.
Term
What is a decorator?
Click to flip
Term
What does the @ syntax do?
Click to flip
This section introduces decorators in Python as a design pattern for modifying function and class behavior without altering their source code.
Decorators serve as wrappers that enhance or change the way functions or class methods behave. This section covers the basics of decorators, including how to create and use them, their syntax, and examples such as logging and parameterized decorators.
Decorators are a powerful feature in Python that enable the modification of a function or class method's behavior without changing its code. They are considered higher-order functions, meaning they can take other functions as input and can also return new functions that are wrapped with additional functionality.
A decorator acts as a wrapper that surrounds a function to enhance or modify its behavior. Instead of changing the code of the function itself, decorators allow programmers to apply modular enhancements. For example, a simple decorator can print messages before and after a function executes.
An example of a simple decorator is the my_decorator function that wraps another function to print messages before and after its execution:
def my_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()In this example, calling say_hello() will produce:
Before the function runs
Hello!
After the function runs
The use of the @ symbol is a syntactical shorthand for applying decorators, allowing for cleaner and more readable code. This essentially transforms say_hello() into a decorated version without the explicit function assignment.
This section highlights the foundational element of decorators in Python programming, which is crucial for the efficient structuring of code to enhance functionality seamlessly.