Search code examples
pythonoutputpython-decorators

Why does this simple code line not work even though it should based on the output?


When function square(x) gets a var it returns var*var. When the function doesn't get a var it returns a list of all the vars that were used.

def square_or_list(func):
    def wrapper(*arg):
        if not arg:
            return last
        else:
            last.append(arg[0])
            func(arg[0])

    last = []
    return wrapper

@square_or_list
def square(x):
    print(x)
    return x**2

print(square(3))
print(square(4))
print(square())

This is the output:

3
None
4
None
[3, 4]

As you can see the program prints the correct x values but doesn't multiply them.


Solution

  • You need to return in your else block as well:

     def wrapper(*arg):
        if not arg:
            return last
        else:
            last.append(arg[0])
            # you need to return for the for a correct recursive call
            return func(arg[0])