V
V
Vyacheslav2020-03-12 16:00:28
Python
Vyacheslav, 2020-03-12 16:00:28

Why does a decorator remove arguments?

Wrote a simple

test.py function

from decorators import decorator_maker
from exceptions import CustomException


@decorator_maker(delay=4)
def decorated_test_func(*args, **kwargs):
    print('Function')
    print('args:', args)
    if args[0] == 1:
        print('Raising exception')
        raise CustomException
    return True


decorated_test_func(2, 5)


decorators.py

from exceptions import CustomException


def decorator_maker(delay=0):
    def do_if_raisen(func):
        def wrap(self, *args, **kwargs):
            try:
                if delay !=0:
                    raise CustomException
                return func(*args, **kwargs)
            except CustomException as e:
                print('delay:', delay) 
                print(e)
                print('Code delayed for {s} sec.'.format(s=delay))
                sleep(delay)
                return func(*args, **kwargs)

        return wrap
    return do_if_raisen


If we run it with a commented line with a decorator,
# @decorator_maker(delay=4)
we get this:
>>python test.py
>>Function
>>args: (2, 5)

If you uncomment it, the result will change dramatically:
>>python test.py
>>delay: 4
>>Message: None

>>Code delayed for 4 sec.
>>Function
>>args: (5,)


Where did the argument from the args tuple go?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-03-12
@ElefanObi

Gone to self, obviously. Start using the debugger and such questions will disappear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question