Get the class name of the decorated class method

Consider this scenario:

import functools

def wrapmethod(f):
    @functools.wraps(f)
    def wrap(*args, **kwargs):
        print '>> %s' % (f.func_name)

        # Here I'll do pre-processing
        r = f(*args, **kwargs)
        # Here I'll do post-processing

        return r

    return wrap

@wrapmethod
def foo():
    pass

class Test(object):
    @wrapmethod
    def foo(self):
        pass

test = Test()
test.foo()
foo()

It will output this, as you can see, done at http://codepad.org/Y4xXyjJO :

>> foo
>> foo

I want to learn how to print Test.fooin the first line, indicating the class with which the method is associated.

Any ideas? Is it ever possible?

Thanks in advance.

+5
source share
2 answers

It's impossible. If you added selfan internal function as the first parameter, you could use it self.__class__.__name__to access the class name, but then it would crash when decorating a classless function without arguments (and if it had arguments, it would consider the first argument self).

, , , , , , .

Btw.. ? , .

+3

, , , "", :

import inspect  
def print_name(*_args):
    def _print_name(fn):
        def wrapper(*args, **kwargs):
            try :
                is_method   = inspect.getargspec(fn)[0][0] == 'self'
            except :
                is_method   = False

            if is_method :
                name    = '{}.{}.{}'.format(fn.__module__, args[0].__class__.__name__, fn.__name__)
            else :
                name    = '{}.{}'.format(fn.__module__, fn.__name__)

            print (name)
        return  fn(*args,**kwargs)
    return wrapper
return _print_name

, ,

+2

Source: https://habr.com/ru/post/1793793/


All Articles