Dynamically Assigning Attributes to Instance Objects #1237
Replies: 1 comment 2 replies
-
Mypy doesn't special-case If you want class That said, if you really want dynamic attributes, you can tell mypy to always allow setting and getting attributes on instances of from typing import Any, TYPE_CHECKING
class A:
if TYPE_CHECKING:
def __getattr__(self, attribute: str) -> Any: ...
def __setattr__(self, attribute: str, value: object) -> None: ... If you want to silence only the error from setattr(self.a, 'b', B()) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I know the
mypy
docs explain:and that
Hence, it makes sense that I can't dynamically add an attribute to an instance variable like so
because that would defeat the purpose (the point of this error is that it's common to accidentally access an attribute that doesn't exist).
But if I explicitly
# type: ignore[attr-defined]
it, is there a reason why asserting ahasattr
doesn't work in another statically typed function?See: this mypy demo
NB: It's most likely better to make
A
aMutableSequence
(override__getitem__
,__setitem__
,__delitem__
,__len__
, and__insert__
) and then do something like:but I am curious if the
hasattr
example is by design for some reason?Beta Was this translation helpful? Give feedback.
All reactions