3

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.

DM_Morpheus
  • 710
  • 2
  • 7
  • 20

1 Answers1

8

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343