Skip to content Skip to sidebar Skip to footer

Python: __qualname__ Of Function With Decorator

I'm using a Decorator (class) in an Instance method of another class, like this: class decorator_with_arguments(object): def __init__(self, arg1=0, arg2=0, arg3=0): se

Solution 1:

You can simply copy the __qualname__ attribute across to your wrapped_f wrapper function; it is this function that is returned when the decorator is applied, after all.

You could use the @functools.wraps() decorator to do this for you, together with other attributes of note:

from functools import wraps

class decorator_with_arguments(object): 
    def __init__(self, arg1=0, arg2=0, arg3=0):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

    def __call__(self, f):
        print("Inside __call__()")
        @wraps(f)
        def wrapped_f(*args):
            print(f.__qualname__)
            f(*args)
        return wrapped_f

The @wraps(f) decorator there copies the relevant attributes from f onto wrapped_f, including __qualname__:

>>> Lol.sayHello.__qualname__
'Lol.sayHello'

Post a Comment for "Python: __qualname__ Of Function With Decorator"