How to get the full class name of a sub-class with Python

Viewed 50

I need to get the full name of a subclass.

Example:

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(x.__class__.__name__)

Output: Bar
Expected: Foo.Bar

2 Answers

You can use the __qualname__, this is the fully qualified name of the __class__

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(x.__class__.__qualname__)
#OUTPUT: Foo.Bar

The best way is to call it on the type, it alredy call __class__ on instance:

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(type(x).__qualname__)
#OUTPUT: Foo.Bar

Use type.

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(type(x))
<class '__main__.Foo.Bar'>

Strip __main__ or not, up to you.

Related