Zeinab Abbasimazar
Zeinab Abbasimazar

Reputation: 10439

got positional argument error when using decorator in python

I have defined a decorator function in python, but I get positional argument error when using it. This is my code:

def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper


@my_upper_case
def print_name(name):
    return name


if __name__ == "__main__":
    print(print_name("zeinab"))

Returned error is:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.

Upvotes: 1

Views: 178

Answers (2)

Finomnis
Finomnis

Reputation: 22476

wrapper wraps the function, meaning it will 'act in its place'.

Therefore, if you call print_name("zeinab"), the wrapper will be called instead with wrapper("zeinab").

wrapper doesn't accept the "zeinab" argument, because you didn't give it any parameters.

def my_upper_case(func):

    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()

    return wrapper


@my_upper_case
def print_name(name):
    return name


if __name__ == "__main__":
    print(print_name("zeinab"))

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599580

As the error says, your wrapper function doesn't accept any arguments. It needs to accept the same args as the function it is wrapping.

def wrapper(arg):
    return func(arg).upper()

Upvotes: 3

Related Questions