Python Forum
How can we override decorator?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can we override decorator?
#1
Let's say I have the following:

@third_party_decorator
def my_method():
  return jsonify(ok=True)
So, can we do like?

@my_decorator(third_party_decorator)
def my_method():
  return jsonify(ok=True)
And define like this?

def my_decorator(decor):
  def _my_deocrator(f)
    print('I am doing something wrong...?'
Reply
#2
There is nothing magical about decorators. A decorator is simply a function with a single argument. It means that your code is absolutely correct as long as the call my_decorator(third_party_decorator) returns a function that accepts a single argument. So don't forget to add return _my_decorator in mydecorator().
>>> def spam(f):
...     return "She sells sea shells by the seashore"
... 
>>> @spam
... def func(x, y, z):
...     return 'func!'
... 
>>> func
'She sells sea shells by the seashore'
Reply
#3
You can combine decorators by stacking them:

def decorator_one(func):
    def wrapper():
        print('decorator #1')
        func()
    return wrapper

def decorator_two(func):
    def wrapper():
        print('decorator the second')
        func()
    return wrapper

@decorator_one
@decorator_two
def hello():
    print('A duck!')

hello()
Output:
decorator #1 decorator the second A duck!
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  the order of running code in a decorator function akbarza 2 526 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Curious about decorator syntax rjdegraff42 14 2,109 May-03-2023, 01:21 PM
Last Post: rjdegraff42
  python update binary object (override delivered Object properties) pierre38 4 1,773 May-19-2022, 07:52 AM
Last Post: pierre38
  dict class override: how access parent values? Andrey 1 1,641 Mar-06-2022, 10:49 PM
Last Post: deanhystad
  Due to MDLable ID does not have get attribute how to override on this jayyu 0 2,833 Dec-20-2021, 10:38 AM
Last Post: jayyu
  Override a library function that is not in __all__ Weird 7 3,292 Aug-23-2021, 05:03 PM
Last Post: Larz60+
  ABC Module and @property decorator, Pythonic Way? muzikman 21 5,681 Aug-18-2021, 06:08 PM
Last Post: muzikman
  decorator adamfairhall 0 1,566 Aug-18-2020, 08:38 AM
Last Post: adamfairhall
  Use of @property decorator ruy 16 6,560 Jun-09-2020, 05:29 PM
Last Post: buran
  Merge dicts without override chisox721 4 3,248 Jul-20-2019, 01:45 AM
Last Post: chisox721

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020