Issue 19073: Inability to specific qualname as a property on a class instance. (original) (raw)
Python 3 introduced qualname. This attribute exists on class types and also instances of certain class types, such as functions. For example:
def f(): pass
print(f.name) print(f.qualname)
class Class: pass
print(Class.name) print(Class.qualname)
yields:
f f Class Class
An instance of a class however does not have name or qualname attributes. With:
c = Class()
print(c.name) print(c.qualname)
yielding:
Traceback (most recent call last): File "qualnametest.py", line 13, in print(c.name) AttributeError: 'Class' object has no attribute 'name'
Traceback (most recent call last): File "qualnametest.py", line 14, in print(c.qualname) AttributeError: 'Class' object has no attribute 'qualname'
For a class, it is possible to override the name attribute using a property.
class Class: @property def name(self): return 'override'
c = Class()
print(c.name)
With the result being:
override
This is useful in writing object proxies or function wrappers for decorators as rather than having to copy the name attribute into the wrapper, the lookup can be deferred until when it is required.
The same though cannot be done for qualname. With:
class Class: @property def qualname(self): return 'override'
yielding an error when the class definition is being processed:
Traceback (most recent call last): File "qualnametest.py", line 16, in class Class: TypeError: type qualname must be a str, not property
This means the same trick cannot be used in object proxies and function wrappers and instead qualname must be copied and assigned explicitly as a string attribute in the init() function of the object proxy or function wrapper.
I can sort of understand a prohibition on qualname being a string attribute in certain cases, especially if overriding it on a type or instance where qualname attribute already exists, but I don't understand why a limitation would be imposed to prevent using a property as a means of generating the value for a class instance which doesn't otherwise have a qualname attribute. There is no similar restriction for name.
Unless there is a good specific reason for this behaviour, the ability to override it with a property in cases where the qualname attribute didn't already exist, would be handy for proxies and wrappers.