1

I want to make an decorator which will take an another decorator function, as an argument.

And an decorator will do additional work.

def raise_error(func):
    def wrapper(*args, **kwargs):
        print('hello from decorator')
        return func(*args, **kwargs)
    return wrapper


@raise_error
def hello():
    return 'Hellom from function'


print(hello())

Technically, I can to write an decorator which will be take, raise_error decorator, and do some additional flow, inside the raise_error decorator?

Thank you in advance.

2 Answers2

0

Are you talking about multiple decorators?

Like this

def raise_error(func):
    def wrapper(*args, **kwargs):
        print('hello from decorator')
        return func(*args, **kwargs)
    return wrapper


def foo(func):
    def wrapper(*args, **kwargs):
        print('bar')
        return func(*args, **kwargs)
    return wrapper


@foo
@raise_error
def hello():
    return 'Hello from function'


print(hello())

Related question: How to make a chain of function decorators?

northtree
  • 8,569
  • 11
  • 61
  • 80
0

Another possibility to have func as param to decorator.

def raise_error(func):
    def wrapper(*args, **kwargs):
        test_func = getattr(func, 'tester', None)
        test_func()
        print('Hello from decorator')
        return func(*args, **kwargs)
    return wrapper


def test():
    print('Hello from test')


def hello():
    print('Hello from function')
    return 'Hello from function'
hello.tester = test


decorated_hello = raise_error(hello)
decorated_hello()

Result:

Hello from test
Hello from decorator
Hello from function
Reck
  • 1,388
  • 11
  • 20