I am manipulating the creation of classes via Python's metaclasses. However, although a class has a attribute thanks to its parent, I can not delete it.
class Meta(type):def __init__(cls, name, bases, dct):super().__init__(name, bases, dct)if hasattr(cls, "x"):print(cls.__name__, "has x, deleting")delattr(cls, "x")else:print(cls.__name__, "has no x, creating")cls.x = 13
class A(metaclass=Meta):pass
class B(A):pass
The execution of the above code yield an AttributeError
when class B
is created:
A has no x, creating
B has x, deleting
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-49e93612dcb8> in <module>()10 class A(metaclass=Meta):11 pass
---> 12 class B(A):13 pass14 class C(B):<ipython-input-3-49e93612dcb8> in __init__(cls, name, bases, dct)4 if hasattr(cls, "x"):5 print(cls.__name__, "has x, deleting")
----> 6 delattr(cls, "x")7 else:8 print(cls.__name__, "has no x, creating")AttributeError: x
Why can't I delete the existing attribute?
EDIT: I think my question is different to delattr on class instance produces unexpected AttributeError which tries to delete a class variable via the instance. In contrast, I try to delete a class variable (alias instance) via the class (alias instance). Thus, the given fix does NOT work in this case.
EDIT2: olinox14 is right, it's an issue of "delete attribute of parent class". The problem can be reduced to:
class A:x = 13
class B(A):pass
del B.x