Search code examples
pythonpython-2.5

How to access class module from object instance?


I want to access module-level variables of the module that defines the class the instance is derived from. I only have the instance to work from. I tried self.__class__.__module__[<some var>] but unlike the __class__ attribute which returns the class object, __module__ just returns a string name, not the module object itself. How can I get the module object in this situation?


Solution

  • The __module__ attribute can be used as a key in the sys.modules dictionary:

    import sys
    class_module = sys.modules[instance.__class__.__module__]