1

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].

Elad Weiss
  • 3,662
  • 3
  • 22
  • 50

1 Answers1

3

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

alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • I agree that the `None` case should be taken into account. Ideally I would like to verify it once in API calls and have the rest of the (helper) functions use preconditions. Regarding your suggestion for `var_2` this is very interesting. I didn't know I can define members without an inital value. Might just be the solution. – Elad Weiss Oct 21 '20 at 11:45
  • Correction, I checked and it seems that defining without an initial value does not really define anything. – Elad Weiss Oct 21 '20 at 11:56