12

How can I get name of class including full path from its module root? For Python 3.3 and up?

Here is example of Python code:

class A:
    class B:
        class C:
            def me(self):
                print(self.__module__)
                print(type(self).__name__)
                print(repr(self))

x = A.B.C()
x.me()

This code outputs me on Python 3.3:

__main__
C
<__main__.A.B.C object at 0x0000000002A47278>

So, Python internally knows that my object is __main__.A.B.C, but how can I get this programmatically? I can parse repr(self), but it sounds like a hack for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bialix
  • 20,053
  • 8
  • 46
  • 63
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1401661/python-list-all-base-classes-in-a-hierarchy-of-given-class please look there for usage info via the `__bases__` attribute and `inspect`module offerings the method resolution order (`mro`) is also interesting info besides the formal inheritance chain "display". As this rules which method (in case multiple are offered) will be chosen kind of like an effective hierarchy. – Dilettant Jun 01 '16 at 12:08
  • 1
    Check the [`__qualname__`](https://docs.python.org/3/whatsnew/3.3.html#pep-3155-qualified-name-for-classes-and-functions) attribute. – Ashwini Chaudhary Jun 01 '16 at 12:15

1 Answers1

13

You are looking for __qualname__ (introduced in Python 3.3):

class A:
    class B:
        class C:
            def me(self):
                print(self.__module__)
                print(type(self).__name__)
                print(type(self).__qualname__)
                print(repr(self))
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • D'oh. I've looked for this attribute and tried to find it using IPython, but tab completion did not show it at all. Not sure why. – bialix Jun 01 '16 at 14:13