Python Forum

Full Version: How can we override decorator?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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...?'
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'
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!