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.

In Python, decorators are functions that conveniently alter functions, methods or classes using a special syntax:

@decorator_function
def python_function():
    '''a python function'''

Which is equivalent to this:

python_function = decorator_function(python_function)

python.org wiki

1888 questions
42
votes
2 answers

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): # (omitted code) return result If I…
WGH
  • 2,562
  • 1
  • 23
  • 37
39
votes
2 answers

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() ret = self.func(*args, **kwargs) …
Rafael T
  • 14,504
  • 14
  • 72
  • 137
39
votes
9 answers

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, thisVarIsAFloat) ''' Here my code ''' pass Side…
AsTeR
  • 6,543
  • 12
  • 54
  • 91
37
votes
1 answer

Applying a decorator to an imported function?

I want to import a function: from random import randint and then apply a decorator to it: @decorator randint I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows: @decorator def…
killajoule
  • 2,762
  • 7
  • 26
  • 34
35
votes
7 answers

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, the scripts are hard to maintain when version…
Timmy Lin
  • 571
  • 5
  • 13
35
votes
2 answers

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 - i.e. the function runs as normal, and if it…
Hugo Rodger-Brown
  • 9,654
  • 7
  • 47
  • 75
31
votes
2 answers

Why no @override decorator in Python to help code readability?

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 that when the subclass overrides the superclass…
gnychis
  • 6,335
  • 15
  • 69
  • 104
28
votes
6 answers

Decorator for a class method that caches return value after first access

My problem, and why I'm trying to write a decorator for a class 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 want it to behave like @property so that it…
Luke Taylor
  • 6,166
  • 7
  • 38
  • 78
27
votes
4 answers

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" @pytest.mark.skipif("platform == 'ios'") def…
Marco Pashkov
  • 3,533
  • 3
  • 32
  • 54
26
votes
3 answers

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)?
itay312
  • 1,024
  • 1
  • 14
  • 30
23
votes
3 answers

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 payload complies with a specific schema Which is…
Adam Matan
  • 107,447
  • 124
  • 346
  • 512
20
votes
3 answers

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 2 instead of 2.23606797749979. What I am trying…
20
votes
1 answer

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 the function definition of the function to be…
con-f-use
  • 3,072
  • 1
  • 31
  • 48
20
votes
1 answer

Python: Use of decorators v/s mixins?

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 inheritance used to inherit from multiple parent…
dev
  • 2,274
  • 7
  • 23
  • 46
19
votes
3 answers

Python decorator, self is mixed up

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): def __init__(self, f): self.f = f …
Rabarberski
  • 21,632
  • 19
  • 69
  • 85