Written by students who passed Immediately available after payment Read online or as PDF Wrong document? Swap it for free 4.6 TrustPilot
logo-home
Other

Decorators in python

Rating
-
Sold
-
Pages
64
Uploaded on
03-08-2023
Written in
2023/2024

Lot of examples Decorators in python

Institution
Course

Content preview

Decorators:
Python decorators allow you to change the behavior of a function without modifying the function
itself.


When to Use a Decorator in Python
You'll use a decorator when you need to change the behavior of a function without modifying the
function itself. A few good examples are when you want to add logging, test performance,
perform caching, verify permissions, and so on.

You can also use one when you need to run the same code on multiple functions. This avoids you
writing duplicating code.

Here are the building blocks used to create Python decorators

To get a better understanding of how decorators work, you should understand a few concepts
first.

• A function is an object. Because of that, a function can be assigned to a variable. The
function can be accessed from that variable.

Example:1

def my_function():

print('I am a function.')

# Assign the function to a variable without parenthesis. We don't want to execute the function.

description = my_function

# Accessing the function from the variable I assigned it to.

print(description())

OUTPUT:

I am a function.

None

How to Create a Python Decorator

,To create a decorator function in Python, I create an outer function that takes a function as an
argument. There is also an inner function that wraps around the decorated function.

Example: 2

Here is the syntax for a basic Python decorator:

def my_decorator_func(func):

def wrapper_func():

# Do something before the function.

func()

# Do something after the function.

return wrapper_func

# To use a decorator ,you attach it to a function like you see in the code below. We use a
decorator by placing the name of the decorator directly above the function we want to use it
on. You prefix the decorator function with an @ symbol.

@my_decorator_func

def my_func():

pass

Output: Empty space em radhu.

,Example: 3

Here is a simple example. This decorator logs the date and time a function is executed:
from datetime import datetime
def log_datetime(func):
'''Log the date and time of a function'''
def wrapper():
print(f'Function: {func.__name__}\nRun on: {datetime.today().strftime("%Y-%m-
%d %H:%M:%S")}')
print(f'{"-"*30}')
func()
return wrapper
@log_datetime
def daily_backup():
print('Daily backup job has finished.')
daily_backup()
OUTPUT:
Function: daily_backup
Run on: 2022-05-13 09:07:14
------------------------------
Daily backup job has finished.



Example: 4

How to Add Arguments to Decorators in Python

Decorators can have arguments passed to them. To add arguments to decorators I add *args and
**kwargs to the inner functions.

*args will take an unlimited number of arguments of any type, such as 10, True, or 'Brandon'.

**kwargs will take an unlimited number of keyword arguments, such as count=99,
is_authenticated=True, or name='Brandon'.

, Here is a decorator with arguments:

def my_decorator_func(func):

def wrapper_func(*args, **kwargs):

# Do something before the function.

func(*args, **kwargs)

# Do something after the function.

return wrapper_func

@my_decorator_func

def my_func(my_arg):

'''Example docstring for function'''

pass

# Decorators hide the function they are decorating. If I check the __name__ or __doc__ method
we get an unexpected result.

print(my_func.__name__)

print(my_func.__doc__)

OUTPUT:

wrapper_func

None

Written for

Institution
Course

Document information

Uploaded on
August 3, 2023
Number of pages
64
Written in
2023/2024
Type
OTHER
Person
Unknown

Subjects

$8.49
Get access to the full document:

Wrong document? Swap it for free Within 14 days of purchase and before downloading, you can choose a different document. You can simply spend the amount again.
Written by students who passed
Immediately available after payment
Read online or as PDF

Get to know the seller
Seller avatar
saimuralidhar

Get to know the seller

Seller avatar
saimuralidhar Andhrapradesh
Follow You need to be logged in order to follow users or courses
Sold
-
Member since
2 year
Number of followers
0
Documents
2
Last sold
-

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Working on your references?

Create accurate citations in APA, MLA and Harvard with our free citation generator.

Working on your references?

Frequently asked questions