Search code examples
pythonintrospection

Getting the module and class of currently executing classmethod in Python


For code that exists in a module named some.module and looks like this:

class MyClass:

 @classmethod
 def method(cls):
  # do something
  pass

I'd like to know in the block marked as "do something" what the module name, the class name, and the method name are. In the above example, that would be:

  • module some.module
  • class MyClass
  • method method

I know of inspect.stack() and I can get the function / method name from it, but I can't find the rest of the data.


Solution

  • These are the most direct ways:

    import inspect
    
    class MyClass:
    
     @classmethod
     def method(cls):
      print("module:", __name__)
      print("class:", cls.__name__)
      print("method:", inspect.currentframe().f_code.co_name)
    

    Doing the same from a utility function requires traversing "back" (up) in the call stack to find the calling frame:

    import inspect
    
    def dbg():
        frame = inspect.currentframe().f_back
        print("module:", frame.f_globals.get("__name__"))
        print("cls:", frame.f_locals.get("cls"))
        print("method:", frame.f_code.co_name)