What is __qualname__ in python?

PythonPython 3.x

Python Problem Overview


  • What is __qualname__ in python and how is it useful?

  • Why would I need to use it over __name__?

I read the https://docs.python.org/3/library/stdtypes.html?highlight=__qualname__#definition.__qualname__">docs</a>;, but they didn't help me get a clear understanding on it's usefulness.

I have read https://stackoverflow.com/questions/37568128/get-fully-qualified-name-of-a-python-class-python-3-3">Get fully qualified name of a Python class (Python 3.3+).
That question asks "how to get a qualified name", which presumes that one knows the meaning of "qualified name". Obviously, the answer to that question is to use the __qualname__ attribute.

My question asks what __qualname__ is, and why should I use it over __name__.

Python Solutions


Solution 1 - Python

__qualname__ gives more complete information than __name__ and therefore can be more helpful in debugging, for example.

Example:

>>> def f(): pass
... class A:
...    def f(self): pass
...    class A:
...        def f(self): pass
...
>>> # __name__ is not showing the path, so these functions look equal
>>> f.__name__
'f'
>>> A.f.__name__
'f'
>>> A.A.f.__name__
'f'
>>> # And these classes looks equal
>>> A.__name__
'A'
>>> A.A.__name__
'A'
>>>
>>> # __qualname__ shows the path, so these functions are distinguishable
>>> f.__qualname__
'f'
>>> A.f.__qualname__
'A.f'
>>> A.A.f.__qualname__
'A.A.f'
>>> # And these classes are distinguishable
>>> A.__qualname__
'A'
>>> A.A.__qualname__
'A.A'

__qualname__ is also adding some backwards compatibility with Python 2's .im_class.

More details in the rationale for PEP 3155

Solution 2 - Python

Just to (potentially) add to the previous answer, __qualname__ can also be called from inside a class, without it having to be bound to any methods. This allows to get a class' name from inside the class when you don't have an __init__ method defined:

class myClass:
    print(__qualname__)

This will return:

myClass

A practical scenario where I found this useful is when working with logging. If you want to implement it in a module with a class that, as stated before, doesn't have an __init__ method, i.e. consists only on class methods, then to add the class' name to the dot-notation path that logging requires to join logs generated by different modules into a single one, __qualname__ seems like an easy solution.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLord ElrondView Question on Stackoverflow
Solution 1 - PythonMattias WallinView Answer on Stackoverflow
Solution 2 - PythonrmoralesdelgadoView Answer on Stackoverflow