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__
.
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.
The qualname option is the name of the logger to log messages for; and the propagate option determines whether messages sent to this logger should also be sent to its parent logger.
A module in Python is a file (ending in .py ) that contains a set of definitions (variables and functions) that you can use when they are imported. Modules are considered as objects, just as everything else is in Python. Many methods can operate on modules.
The first and easiest method to get a class name in python is by using __class__ property which basically refers to the class of the object we wish to retrieve. Here we combine the property with __name__ property to identify the class name of the object or instance.
__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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With