Get the class name where the method is defined in the decorator

A memo when I had a hard time getting the class name when logging the method execution time

Thing you want to do

I want to display the class name and method name when logging with a decorated method to find out which method is running at what time

try1

Implementation content

Try to decorate normally

def deco(func):
    def inner(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        print 'class: %s, method: %s' % (
            func.im_class.__name__,
            func.__name__)
        #Logging process
        return result
    return inner

Result: error

func was passed as a function and didn't have im_class. For this reason, I could get the method name, but not the class name.

try2

Implementation content

Get the class name from self.

def deco(func):
    def inner(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        print 'class: %s, method: %s' % (
            self.__class__.__name__,
            func.__name__)
        #Logging process
        return result
    return inner

Result: error?

NG because the subclass name will be returned when inheriting

try3

Implementation content

Decorate the class.

def deco_cls(cls):
    def deco_method(func):
        def inner(self, *args, **kwargs):
            result = func(self, *args, **kwargs)
            print 'class: %s, method: %s' % (
                cls.__name__,
                func.__name__)
            #Logging process
            return result
        return inner

    for name, method in cls.__dict__.items():
        if name == 'target_func':
            setattr(cls, name, deco_method(method))
    return cls

Result: OK

It is compared as target_func, but in the version actually used, the target method name was prepared as a tuple and compared. If you want to specify the target method clearly, you can also use the following method.

def deco_cls(cls):
    def deco_method(func):
        def inner(self, *args, **kwargs):
            result = func(self, *args, **kwargs)
            print 'class: %s, method: %s' % (
                cls.__name__,
                func.__name__)
            #Logging process
            return result
        return inner

    for name, method in cls.__dict__.items():
        if hasattr(method, 'set_logger'):
            setattr(cls, name, deco_method(method))
    return cls

def set_logger_wrapper(func):
    func.set_logger = True
    return func

Recommended Posts

Get the class name where the method is defined in the decorator
Automatically get the port where Arduino is stuck in Python
Get the host name in Python
Unfortunately there is no sense of unity in the where method
Get the region where AWS Lambda is running
Write decorator in class
How to get the variable name itself in python
Get the file name in a folder using glob
[python] Get the list of classes defined in the module
When a local variable with the same name as a global variable is defined in the function
How to use the __call__ method in a Python class
Decorator that displays "FIN method name" at the end of the method
Get the file name saved in AWS S3 (1000 or more)
I want to get the name of the function / method being executed
How is the progress? Let's get on with the boom ?? in Python
Format the Git log and get the committed file name in csv format
Get the desktop path in Python
Get the script path in Python
Gender is determined from the name.
Examine the object's class in python
Get the desktop path in Python
Get the query string (query string) in Django
Find out the name of the method that called it from the method that is python
How to get the "name" of a field whose value is limited by the choice attribute in Django's model
[Python] Name Error: name'urlparse' is not defined
Get the top nth values in Pandas
[Python] Get the variable name with str
Where is the python instantiation process written?
Learn the design pattern "Decorator" in Python
What is "mahjong" in the Python library? ??
When the target is Ubuntu 16.04 in Ansible
I can't get the element in Selenium!
Get the EDINET code list in Python
Get the hierarchy name using the OpenMaya iterator
Is there NaN in the pandas DataFrame?
The date is displayed incorrectly in matplotlib.
I want to get the path of the directory where the running file is stored.
[pandas] When specifying the default Index label in the at method, "" is not required
When I name the file flask.py in Flask, I get Import Error: cannot import name'Flask'
You can call the method of the class directly in Python3 without adding @staticmethod
How to get the notebook name you are currently using in Google Colab
In Python, change the behavior of the method depending on how it is called
I want to get the file name, line number, and function name in Python 3.4
I didn't have to write a decorator in the class Thank you contextmanager