0
def logging_decorator(function):
    def wrapper(*args, **kwargs):
        print(f'This is {function.__name__}')
        output = function(*args, **kwargs)
    return wrapper


@logging_decorator
def a_function(a, b, c):
    print(f'This is the Function name {a_function.__name__}')
    return a * b * c

object = a_function(3, 4, 5)

Been playing around with python decorators and I don't understand the following:

Why does

print(f'This is the Function name {a_function.__name__}')

output 'This is the Function name wrapper'? Shouldn't the output be 'This is the Function name a_function' instead?

Paul Ged
  • 53
  • 9

1 Answers1

0

After your function is defined.

a_function = def (a, b, c){...}

The wrapper will wrap your function. You can imaginate like this:

a_function = logging_decorator(a_function)

And the function logging_decorator return a function name wrapper. Now, a_function is just a reference, that linked to function wrapper

To get what you expect, I tried this:

from functools import wraps

def logging_decorator(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        print(f'This is {function.__name__}')
        output = function(*args, **kwargs)
    return wrapper


@logging_decorator
def a_function(a, b, c):
    print(f'This is the Function name {a_function.__name__}')
    return a * b * c

@logging_decorator
def b_function(a, b, c):
    print(f'This is the Function name {b_function.__name__}')
    return a * b * c

object = a_function(3, 4, 5)
object = b_function(3, 4, 5)

And it solve your problem.

Sihc
  • 59
  • 6