qualname
The `qualname` Python module emulates the `__qualname__` attribute for classes and methods in older Python versions (specifically pre-Python 3.3). Introduced in PEP 3155, `__qualname__` provides a 'qualified name' including the full dotted path to an object within its module, which is particularly useful for nested definitions. This library achieves this by performing source code inspection and abstract syntax tree (AST) parsing, which means the source file must be available at runtime. The current version is 0.1.0, and its release cadence is infrequent, as its primary utility lies in supporting older Python environments.
Warnings
- gotcha The library relies on source code inspection, meaning the source file must be available for `qualname()` to work. For objects like built-in types, or when the source cannot be determined (e.g., in some dynamically generated code), it may fall back to `__name__` or raise errors.
- gotcha This library is primarily intended for Python versions older than 3.3. In Python 3.3 and later, the `__qualname__` attribute is a built-in feature of classes and functions, making this library redundant for those versions.
- gotcha The `__qualname__` attribute (whether native or emulated by this library) provides the dotted path within a module but does NOT include the module name itself. Users often expect a 'fully qualified name' that includes the module (e.g., `my_module.MyClass.my_method`).
- gotcha For inherited methods, `__qualname__` will report the qualified name from the class where the method was *defined*, not necessarily the class from which it is being accessed if the method is not overridden. This can lead to unexpected results if you expect `__qualname__` to always reflect the current class hierarchy.
Install
-
pip install qualname
Imports
- qualname
from qualname import qualname
Quickstart
import sys
from qualname import qualname
class Outer:
def method_a(self):
pass
class Inner:
def method_b(self):
pass
def top_level_func():
def nested_func():
pass
return nested_func
# For Python < 3.3, this library provides __qualname__ functionality
# On Python 3.3+, objects already have __qualname__
print(f"Python Version: {sys.version.split(' ')[0]}")
print(f"Outer.__qualname__: {qualname(Outer)}")
print(f"Outer.method_a.__qualname__: {qualname(Outer.method_a)}")
print(f"Outer.Inner.__qualname__: {qualname(Outer.Inner)}")
print(f"Outer.Inner.method_b.__qualname__: {qualname(Outer.Inner.method_b)}")
nested_f = top_level_func()
print(f"top_level_func.__qualname__: {qualname(top_level_func)}")
print(f"nested_f.__qualname__: {qualname(nested_f)}")