Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Decorator

python decorator

Uploaded by

rohittestuser255
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Decorator

python decorator

Uploaded by

rohittestuser255
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

8/6/24, 3:18 PM Python decorator? - can someone please explain this?

- Stack Overflow

1 Nope, you could name it @discombobulated if you wanted to. Decorators are just functions. – Blender
Aug 21, 2012 at 20:54

Take a look at this. It's a great explanation of decorators in python. – Jaydip Kalkani Apr 18, 2018 at 5:43

Since some people like to learn in video format, here is the best explanation I've watched of Python
decorators. In this video (click link to be taken to the start of the topic) James Powell takes you though the
entire history of decorators so you get a very clear picture of the why and how. youtu.be/cKPlPJyQrt4?
t=3099 – CodyBugstein Mar 11, 2019 at 16:50

7 Answers Sorted by: Highest score (default)

Take a good look at this enormous answer/novel. It's one of the best explanations I've come
across.
51
The shortest explanation that I can give is that decorators wrap your function in another function
that returns a function.

This code, for example:

@decorate
def foo(a):
print a

would be equivalent to this code if you remove the decorator syntax:

def bar(a):
print a

foo = decorate(bar)

Decorators sometimes take parameters, which are passed to the dynamically generated functions
to alter their output.

Another term you should read up on is closure, as that is the concept that allows decorators to
work.

Share Follow edited May 23, 2017 at 12:34 answered Aug 21, 2012 at 0:26
Community Bot Blender
1 1 296k 54 448 506

A decorator is a function that takes a function as its only parameter and returns a function. This is
helpful to “wrap” functionality with the same code over and over again.
22
We use @func_name to specify a decorator to be applied on another function.

https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this 2/11
8/6/24, 3:18 PM Python decorator? - can someone please explain this? - Stack Overflow
do_upload_ajax = protected(check_valid_user)(do_upload_ajax)

but without the need to repeat the same name three times. There is nothing more to it.

For example, here's a possible implementation of protected() :

import functools

def protected(check):
def decorator(func): # it is called with a function to be decorated
@functools.wraps(func) # preserve original name, docstring, etc
def wrapper(*args, **kwargs):
check(bottle.request) # raise an exception if the check fails
return func(*args, **kwargs) # call the original function
return wrapper # this will be assigned to the decorated name
return decorator

Share Follow edited Aug 21, 2012 at 10:32 answered Aug 21, 2012 at 0:56
jfs
410k 201 1k 1.7k

Does "protected" mean anything specific? – Duke Dougal Aug 21, 2012 at 1:54

1 @Duke: It is just a name. You could use any. – jfs Aug 21, 2012 at 10:35

A decorator is a function that takes another function and extends the behavior of the latter
function without explicitly modifying it. Python allows "nested" functions ie (a function within
7 another function). Python also allows you to return functions from other functions.

Let us say, your original function was called orig_func().

def orig_func(): #definition


print("Wheee!")

orig_func() #calling

Run this file, the orig_func() gets called and prints. "wheee".

Now, let us say, we want to modify this function, to do something before this calling this function
and also something after this function.

So, we can do like this, either by option 1 or by option 2

--------option 1----------

https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this 4/11
8/6/24, 3:18 PM Python decorator? - can someone please explain this? - Stack Overflow
orig_func = my_decorator(orig_func) #create decorator, modify functioning
orig_func() #call modified orig_func

==============================================================
=

Note, that now orig_func has been modified through the decorator. So, now when you call
orig_func(), it will run my_wrapper, which will do three steps, as already outlined.

Thus you have modified the functioning of orig_func, without modifying the code of orig_func,
that is the purpose of the decorator.

Share Follow answered Dec 3, 2017 at 7:15


M Shiraz Baig
123 1 3

Great answer ! Explained well. – Mandar Pande Oct 24, 2018 at 15:06

2 can you add a few lines after the last code block, to show how it looks like using @ and decorator
grammar? – athos Jun 20, 2019 at 4:32

Decorator is just a function that takes another function as an argument

Simple Example:
3
def get_function_name_dec(func):
def wrapper(*arg):
function_returns = func(*arg) # What our function returns
return func.__name__ + ": " + function_returns

return wrapper

@get_function_name_dec
def hello_world():
return "Hi"

print(hello_world())

Share Follow answered Sep 4, 2019 at 11:34


mikazz
179 2 12

https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this 6/11
8/6/24, 3:18 PM Python decorator? - can someone please explain this? - Stack Overflow

Then, we can get the result below:

Now, we can use minus_2() as a decorator with sum() as shown below:

# (4 + 6) - 2 = 8

def minus_2(func):
def core(*args, **kwargs):
result = func(*args, **kwargs)
return result - 2
return core

@minus_2 # Here
def sum(num1, num2):
return num1 + num2

result = sum(4, 6)
print(result)

Then, we can get the same result below:

Next, we created times_10() to multiply the result of minus_2() by 10 as shown below:

# ((4 + 6) - 2) x 10 = 80

def minus_2(func):
def core(*args, **kwargs):
result = func(*args, **kwargs)
return result - 2
return core

def times_10(func): # Here


def core(*args, **kwargs):
result = func(*args, **kwargs)
return result * 10
return core

def sum(num1, num2):


return num1 + num2

f1 = minus_2(sum)
f2 = times_10(f1)
result = f2(4, 6)
print(result)

In short:

https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this 8/11
8/6/24, 3:18 PM Python decorator? - can someone please explain this? - Stack Overflow

80

So, if we change the order of them as shown below:

# ((4 + 6) * 10) - 2 = 98

@minus_2 # 2nd executed.


@times_10 # 1st executed.
def sum(num1, num2):
return num1 + num2

Then, we can get the different result below:

98

Lastly, we created the code below in Django to run test() in transaction by @tran :

# "views.py"

from django.db import transaction


from django.http import HttpResponse

def tran(func): # Here


def core(request, *args, **kwargs):
with transaction.atomic():
return func(request, *args, **kwargs)
return core

@tran # Here
def test(request):
person = Person.objects.all()
print(person)
return HttpResponse("Test")

Share Follow edited Nov 24, 2022 at 12:33 answered Nov 12, 2022 at 19:04
Super Kai - Kazuya Ito
1

I'm going to use a code to response this.

What I need?: I need to modify math.sin()'s definition to add 1 always to the sine of a value
0
Problem: I do not have math.sin() code

Solution: Decorators

import math

https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this 10/11

You might also like