问题
I have a codebase which I would like to validate using mypy. In the current design, it is very common that a class may have a non-primitive member that can be set later after __init__
.
So, in __init__
the member is initialized to None
and its type becomes Optional
accordingly.
The problem is that now MyPy
requires me to check that the member is not None
every time it is being used.
As a quick solution I can add assert self._member is not None # MyPy
in all the relevant scopes, but it seems like a very bad practice.
Another idea would be to add a @property
and do the assertion inside, but this also seems like a huge overhead.
Is there a more natural/correct design that can overcome this issue?
Edit:
To clarify, my code is fully type annotated.
The member definition is self._member: Optional[MemberType]
.
回答1:
If an instance variable is assigned outside of __init__
, then an instance of the class may be in a state where the variable is not set. And to be honest, this should be taken into account in the functions using it. But if we believe or ensure that these functions will not be called in this state, then we can annotate this instance member as follows:
class Foo:
var_1: int # variant 1
def __init__(self) -> None:
self.var_2: int # variant 2
These statements do not create real variables, only annotations of instance variables that will be taken into account by the mypy
来源:https://stackoverflow.com/questions/64462059/refactor-to-meet-mypy-requirements