What Is __qualname__ in Python

The __qualname__ attribute means qualified name in Python. It gives you a dotted path to the name of the target object.

Using __qualname__ is useful with nested structures, such as when you have a method inside a class.

For example:

class Example:
    def something():
        pass

print(Example.something.__qualname__)

The result of this is a full path to the attribute:

Example.something

__qualname__ vs __name__ in Python

In Python, there is another similar attribute called __name__. This attribute also shows the naming information about an object.

For example:

class Example:
    pass

print(Example.__name__)

Output:

Example

If you compare this to the __qualname__ attribute:

class Example:
    pass

print(Example.__qualname__)

Output:

Example

You see that both attributes gave the same result.

But what is the difference between the two?

With nested structures, the __qualname__ returns a path to the object. The __name__ attribute does not.

For example:

class Example:
    def something():
        pass

print(Example.something.__name__)
print(Example.something.__qualname__)

Output:

something
Example.something

Here the __qualname__ returns the path to something method inside the Example class. The __name__ attribute does not do this as it merely knows the name of the method.

Using __qualname__ is useful if you have a function and a method with the same names. Using __qualname__ you are able to see the difference between the method and the function based on the path it returns.

def something():
    pass

class Example:
    def something():
        pass

print(something.__qualname__)
print(Example.something.__qualname__)

Output:

something
Example.something

But using only the __name__ attribute you would not be able to tell the difference. This is because the __name__ does not return a full path to the object.

For example:

def something():
    pass

class Example:
    def something():
        pass

print(something.__name__)
print(Example.something.__name__)

Output:

something
something

Another useful feature of  __qualname__ is it can be called in the class. You can access the name of the class from within even if you do not have an __init__ method specified.

For example:

class Example:
    print(__qualname__)

Output:

Example

Conclusion

Today you learned what is the __qualname__ attribute in Python.

To recap, the __qualname__ attribute returns a complete path to an object. This is useful information when dealing with nested structures, such as when you have a class with a method.

Further Reading

50 Python Interview Questions