Search code examples
pythonpython-datamodel

Get fully qualified class name of an object in Python


For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)

I know about x.__class__.__name__, but is there a simple method to get the package and module?


Solution

  • With the following program

    #!/usr/bin/env python
    
    import foo
    
    def fullname(o):
        klass = o.__class__
        module = klass.__module__
        if module == 'builtins':
            return klass.__qualname__ # avoid outputs like 'builtins.str'
        return module + '.' + klass.__qualname__
    
    bar = foo.Bar()
    print(fullname(bar))
    

    and Bar defined as

    class Bar(object):
      def __init__(self, v=42):
        self.val = v
    

    the output is

    $ ./prog.py
    foo.Bar
    

    If you're still stuck on Python 2, you'll have to use __name__ instead of __qualname__, which is less informative for nested classes - a class Bar nested in a class Foo will show up as Bar instead of Foo.Bar:

    def fullname(o):
        klass = o.__class__
        module = klass.__module__
        if module == '__builtin__':
            return klass.__name__ # avoid outputs like '__builtin__.str'
        return module + '.' + klass.__name__