Questions tagged [python-decorators]
In Python, decorators are functions that conveniently alter functions, methods or classes using a special syntax. Decorators dynamically alter the functionality without changing the source code being decorated.
python-decorators
2,479
questions
4681
votes
36
answers
1.1m
views
What is the difference between @staticmethod and @classmethod in Python?
What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
3168
votes
22
answers
664k
views
How do I make function decorators and chain them together?
How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i>&...
1377
votes
14
answers
794k
views
How does the @property decorator work in Python?
I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and ...
290
votes
9
answers
260k
views
Class method decorator with self arguments?
How do I pass a class field to a decorator on a class method as an argument? What I want to do is something like:
class Client(object):
def __init__(self, url):
self.url = url
@...
192
votes
5
answers
73k
views
`staticmethod` and `abc.abstractmethod`: Will it blend?
In my Python app I want to make a method that is both a staticmethod and an abc.abstractmethod. How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
import abc
class ...
175
votes
3
answers
75k
views
Decorator execution order
def make_bold(fn):
return lambda : "<b>" + fn() + "</b>"
def make_italic(fn):
return lambda : "<i>" + fn() + "</i>"
@make_bold
@make_italic
def hello():
return "...
154
votes
10
answers
76k
views
Real world example about how to use property feature in python?
I am interested in how to use @property in Python. I've read the python docs and the example there, in my opinion, is just a toy code:
class C(object):
def __init__(self):
self._x = None
...
138
votes
6
answers
109k
views
How do I pass extra arguments to a Python decorator?
I have a decorator like below.
def myDecorator(test_func):
return callSomeWrapper(test_func)
def callSomeWrapper(test_func):
return test_func
@myDecorator
def someFunc():
print 'hello'
I ...
100
votes
10
answers
58k
views
Python functools lru_cache with instance methods: release object
How can I use functools.lru_cache inside classes without leaking memory?
In the following minimal example the foo instance won't be released although going out of scope and having no referrer (other ...
88
votes
2
answers
22k
views
Make @lru_cache ignore some of the function arguments
How can I make @functools.lru_cache decorator ignore some of the function arguments with regard to caching key?
For example, I have a function that looks like this:
def find_object(db_handle, query):...
83
votes
6
answers
41k
views
How to do a conditional decorator in python?
Is it possible to decorate a function conditionally? For example, I want to decorate the function foo() with a timer function (timeit), but only when doing_performance_analysis condition is True, like ...
80
votes
3
answers
47k
views
Decorating class methods - how to pass the instance to the decorator?
This is Python 2.5, and it's GAE too, not that it matters.
I have the following code. I'm decorating the foo() method in bar, using the dec_check class as a decorator.
class dec_check(object):
def ...
75
votes
8
answers
85k
views
How to create a custom decorator in Django?
I'm trying to create a custom decorator in Django but I couldn't find any ways to do it.
# "views.py"
@custom_decorator
def my_view(request):
# .......
So, how can I create it in ...
73
votes
11
answers
52k
views
How to inject variable into scope with a decorator?
[Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python's scoping works here]
I'm trying to find a way to make a decorator that does something like ...
71
votes
4
answers
60k
views
Python 3 type hinting for decorator
Consider the following code:
from typing import Callable, Any
TFunc = Callable[..., Any]
def get_authenticated_user(): return "John"
def require_auth() -> Callable[TFunc, TFunc]:
...
70
votes
5
answers
5k
views
How to bypass python function definition with decorator?
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:
@linux
def my_callback(*args, **kwargs):
print("Doing something @ Linux")
...
70
votes
4
answers
25k
views
Is a Python Decorator the same as Java annotation, or Java with Aspects?
Are Python Decorators the same or similar, or fundamentally different to Java annotations or something like Spring AOP, or Aspect J?
62
votes
5
answers
47k
views
How to add a custom decorator to a FastAPI route?
I want to add an auth_required decorator to my endpoints.
(Please consider that this question is about decorators, not middleware)
So a simple decorator looks like this:
def auth_required(func):
...
59
votes
1
answer
22k
views
How can I apply a decorator to an imported function? [duplicate]
Suppose I have imported a function:
from random import randint
and then want to apply a decorator to it. Is there some syntactic sugar for this, perhaps something like so?
@decorator
randint
Or do I ...
51
votes
3
answers
30k
views
How can I decorate an instance method with a decorator class?
Consider this small example:
import datetime as dt
class Timed(object):
def __init__(self, f):
self.func = f
def __call__(self, *args, **kwargs):
start = dt.datetime.now()
...
50
votes
7
answers
26k
views
Python decorator? - can someone please explain this? [duplicate]
Apologies this is a very broad question.
The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does ...
49
votes
10
answers
55k
views
How to use Python decorators to check function arguments?
I would like to define some generic decorators to check arguments before calling some functions.
Something like:
@checkArguments(types = ['int', 'float'])
def myFunction(thisVarIsAnInt, ...
47
votes
4
answers
35k
views
How to skip a pytest using an external fixture?
Background
I am running a py.test with a fixture in a conftest file. You can see the code below(this all works fine):
example_test.py
import pytest
@pytest.fixture
def platform():
return "ios"
...
47
votes
2
answers
45k
views
Why no @override decorator in Python to help code readability? [closed]
I've been using abstract classes in Python with ABCMeta. When you write an abstract method you tag it with the decorator @abstractmethod. One thing that I found odd (and unlike other languages) is ...
44
votes
2
answers
27k
views
How can I get a Python decorator to run after the decorated function has completed?
I want to use a decorator to handle auditing of various functions (mainly Django view functions, but not exclusively). In order to do this I would like to be able to audit the function post-execution -...
38
votes
3
answers
18k
views
React js - What is the difference betwen HOC and decorator
Can someone explain what is the difference between these two?
I mean except the syntactic difference, do both of these techniques are used to achieve the same thing (which is to reuse component logic)?...
37
votes
7
answers
6k
views
Same name functions in same class - is there an elegant way to determine which to call?
I am trying to do product version control in Python scripts for a specific reason, but I couldn't figure out how to do it in an elegant way.
Currently, I am doing something like the below. However, ...
35
votes
1
answer
12k
views
How can one attach a decorator to a function "after the fact" in python?
The way I understand decorators of function in python (and I might be wrong), is that they are supposed to add side effects and modify the return value of a function. Now decorators are added above ...
30
votes
9
answers
26k
views
Decorator for a method that caches return value after first access
My problem, and why
I'm trying to write a decorator for a method, @cachedproperty. I want it to behave so that when the method is first called, the method is replaced with its return value. I also ...
28
votes
3
answers
29k
views
Flask: Decorator to verify JSON and JSON Schema
I have a flask application with calls expecting JSON payload. Before each call is processed, I have a 2-step error checking process:
Assert that the payload is a valid JSON
Assert that the JSON ...
28
votes
4
answers
8k
views
Why do we need wrapper function in decorators?
If I create a decorator like the following:
def my_decorator(some_fun):
def wrapper():
print("before some_fun() is called.")
some_fun()
print("after some_fun(...
27
votes
3
answers
37k
views
descriptor '__init__' of 'super' object needs argument
I'm trying my hand at making an Object-Oriented text-based game in Python, and attempting to implement my first properties and decorators. Using the chapter 5 in the book 'Python 3 Object Oriented ...
27
votes
2
answers
4k
views
Can someone explain how the source code of staticmethod works in python
First of all, I understand how, in general, a decorator work. And I know @staticmethod strips off the instance argument in the signature, making
class C(object):
@staticmethod
def foo():
...
26
votes
2
answers
10k
views
Class properties in Python 3.11+
In Python 3.9, we gained the ability to chain @classmethod and @property to sensibly create class properties.
class Foo:
@property
def instance_property(self):
return "A regular property&...
25
votes
1
answer
5k
views
Python: Use of decorators v/s mixins? [closed]
I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple ...
22
votes
3
answers
7k
views
Difference between Context Managers and Decorators in Python
What is the main difference between the two? I have been studying Python and came across them. A decorator is essentially a function that wraps another function and you can do anything before and ...
22
votes
1
answer
16k
views
Can variables be decorated?
Decorating function or method in python is wonderful.
@dec2
@dec1
def func(arg1, arg2, ...):
pass
#This is equivalent to:
def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))
I was ...
22
votes
5
answers
13k
views
How to disable skipping a test in pytest without modifying the code?
I have inherited some code that implements pytest.mark.skipif for a few tests. Reading through the pytest docs, I am aware that I can add conditions, possibly check for environment variables, or use ...
21
votes
2
answers
19k
views
How to write Flask decorator with request?
I am not sure why following decorator[validate_request] doesn't work. What is correct way to write such validation decorator?
def validate_request(req_type):
if req_type is 'json' and not ...
21
votes
1
answer
6k
views
Function decorators with parameters on a class based view in Django
The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator.
I would like to achieve something like
...
21
votes
5
answers
10k
views
Is it possible to numpy.vectorize an instance method?
I've found that the numpy.vectorize allows one to convert 'ordinary' functions which expect a single number as input to a function which can also convert a list of inputs into a list in which the ...
21
votes
2
answers
4k
views
Scope of variables in python decorator
I'm having a very weird problem in a Python 3 decorator.
If I do this:
def rounds(nr_of_rounds):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
return ...
20
votes
5
answers
13k
views
Check if a function uses @classmethod
TL;DR How do I find out whether a function was defined using @classmethod or something with the same effect?
My problem
For implementing a class decorator I would like to check if a method takes the ...
20
votes
3
answers
2k
views
How to make a function composer
I am trying to make a function that rounds other functions for my university degree . For example I would like to call the round_sqrt = round(sqrt)
and when i call the round_sqrt(5) it has to shows me ...
20
votes
3
answers
9k
views
Python decorator, self is mixed up [duplicate]
I am new to Python decorators (wow, great feature!), and I have trouble getting the following to work because the self argument gets sort of mixed up.
#this is the decorator
class cacher(object):
...
20
votes
2
answers
5k
views
Making abstract property in Python 3 results in AttributeError
How do you make an abstract property in python?
import abc
class MyClass(abc.ABC):
@abc.abstractmethod
@property
def foo(self):
pass
results in the error AttributeError: attribute ...
20
votes
3
answers
11k
views
How to get source code of function that is wrapped by a decorator?
I wanted to print the source code for my_func, that is wrapped by my_decorator:
import inspect
from functools import wraps
def my_decorator(some_function):
@wraps(some_function)
def wrapper()...
20
votes
1
answer
19k
views
mypy: Untyped decorator makes function "my_method" untyped
When I try using a decorator that I defined in another package, mypy fails with the error message Untyped decorator makes function "my_method" untyped. How should I define my decorator to ...
19
votes
3
answers
17k
views
Decorator to set attribute of function
I want different functions to be executable only if the logged in user has the required permission level.
To make my life more simple I want to use decorators. Below I attempt to set attribute ...
19
votes
3
answers
2k
views
Merging Python decorators with arguments into a single one [duplicate]
I'm using two different decorators from two different libraries. Lets say: @decorator1(param1, param2) and @decorator2(param3, param4). That I often use in many functions as:
from moduleA import ...