-
Notifications
You must be signed in to change notification settings - Fork 48
Description
Native classes don't have __dict__ so dynamic attributes have to be implemented using a custom dictionary, eg.
class Test:
_attributes: dict[str, object] = {}
def __setattr__(self, key: str, val: object) -> None:
self._attributes[key] = val
def __getattr__(self, key: str) -> object:
return self._attributes.get(key)One difference between using a custom dictionary and __dict__ is that with a custom dictionary, __delattr__ needs to be defined if the class should support deleting the dynamic attributes, eg.
i = Test()
i.new_attr = 1
del i.new_attrBy default, del deletes from __dict__ so this raises an AttributeError.
It's technically correct and the same as interpreted python but when someone converts a class with dynamic attributes into a native one, they might forget about __delattr__ and not learn about it until they try to execute a del statement.
It could be helpful if mypyc reported this at compile time since it can see that Test does not have __dict__ and new_attr is not defined as a static attribute so __delattr__ is needed.
Also consider if this could be extended to delattr(i, "new_attr") and object.__delattr__(i, "new_attr")