Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

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

class Lol:
    @decorator_with_arguments("hello")
    def sayHello(self,a1, a2, a3, a4):
        print(self.sayHello.__qualname__)

Now, when I print out self.sayHello.__qualname__ it prints decorator_with_arguments.__call__.<locals>.wrapped_f

Is there any way to override this? I want to see Lol.sayHello (qualname of my original function) in here.

I tried overriding the @property __qualname__ of __call__ (with a static string); didn't work.

like image 610
DM_Morpheus Avatar asked May 23 '26 16:05

DM_Morpheus


1 Answers

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'
like image 182
Martijn Pieters Avatar answered May 25 '26 08:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!