Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is __qualname__ in python?

  • 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__.

like image 389
Lord Elrond Avatar asked Sep 26 '19 01:09

Lord Elrond


People also ask

What is __ Qualname __?

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.

What is Qualname in Python logging?

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.

What is __ module __ in Python?

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.

How do I get the class name of an object in Python?

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.


1 Answers

__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

like image 157
Mattias Wallin Avatar answered Oct 01 '22 12:10

Mattias Wallin