Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get fully qualified name of a Python class (Python 3.3+)

Tags:

python

inspect

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.

like image 845
bialix Avatar asked Jun 01 '16 12:06

bialix


People also ask

How to get the class name in Python?

A class is a data structure, and it can hold both data members and member methods. This tutorial will discuss the method to get the class name in Python. type () is a predefined function that can be used in finding the type or class of an object.

How do you find the type of an object in Python?

Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance The __class__ property can also be used to find the class or type of an object. It basically refers to the class the object was created in. The __name__ can also be used along with __class__ to get the class of the object.

What is the difference between a qualified name and a path?

“Qualified name” is the best approximation, as a short phrase, of what the additional attribute is about. It is not a “full name” or “fully qualified name” since it (deliberately) does not include the module name. Calling it a “path” would risk confusion with filesystem paths and the __file__ attribute.


1 Answers

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))
like image 86
Sean Vieira Avatar answered Oct 23 '22 13:10

Sean Vieira