Search code examples
pythoncpythoninspect

Python - Can not get object of class method at runtime to extract doc-string


I'm trying to get a doc-string of a class method at runtime. The problem I'm facing is that the method is not recorded in globals() at runtime.

Below is the code that Illustrates that a normal function is recorded in globals but a class method is not.

import datetime, inspect

class Age:
    """
    test Ager DOCstring
    """

    def __init__(self):
        pass

    def get_age(self, yob):
        """
        Calculate age using date of birth.
        """
        outerframe = inspect.currentframe()
        functionname = outerframe.f_code.co_name
        func_details = globals()[ functionname ]
        print('class_method:', func_details)

        year_today = datetime.datetime.today().year
        age = year_today-yob
        return age


def calc_age(yob):
    outerframe = inspect.currentframe()
    functionname = outerframe.f_code.co_name
    func_details = globals()[ functionname ]
    print('normal_function:', func_details)

    year_today = datetime.datetime.today().year
    age = year_today-yob
    return age


if __name__ == "__main__":
    calc_age(1998)
    ager = Age()
    ager.get_age(1990) # will raise KeyError

What is the cause of this behavior and how can I solve it?


Solution

  • Your method is not a global value, it exists as an attribute on your class. You can find it in the classes __dict__-attribute however:

    Age.__dict__['get_age']