0

Let's suppose I have a simple function returning its own name

def foo():
    print(foo.__name__)

Of course the output when calling is foo. However, if we now decorate that function with a decorator like this:

def dec(func):
    print(dec.__name__)

    def wrapper(*args):
        print(wrapper.__name__)
        return func(*args)
    return wrapper


@dec
def foo():
    print(foo.__name__)


foo()

We get

dec
wrapper
wrapper

Why is the name of the inner function called here? func(*args) is specifically called, shouldn't it be really the function's name among with dec wrapper?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Raumschifffan
  • 360
  • 2
  • 13

1 Answers1

1

As for the reason what the decorator does is replace your original function with the wrapper. So in fact foo isn’t foo anymore, it is the closure created by combining wrapper and func.

wraps is a trick to transfer such metadata to the newly created function.

rudolfovic
  • 3,163
  • 2
  • 14
  • 38