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

  • Why would I need to use it over __name__?

I read the docs, but they didn't help me get a clear understanding on it's usefulness.

I have read 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__.

2
@Selcuk How is that a duplicate? I am asking what __qualname__ is and how it is used, not How do I get the fully qualified name... - Lord Elrond
The question you linked has no explanation about what it does or what it is used for. - Lord Elrond
You are looking for __qualname__ (introduced in Python 3.3): - Lord Elrond
I don't consider that an explanation for what __qualname__ is. - Lord Elrond
You might want to elaborate on why the docs didn't help you understand what a qualified name is. I find the explanation pretty straight forward. Helping us understand your lack of understanding helps us provide a proper explanation that hopefully helps you understand. - Max Vollmer

2 Answers

47
votes

__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

12
votes

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.