I have class member which is either None or a dict.
I have a method for the lengths of that member that returns None if the
member is None or the size of the dictionary if it exists:
class A:
def __init__(self, a: bool = False) -> None:
self.has_a = a
self.prop_a = {"a" : 1} if a else None
def length_prop(self) -> int:
length_prop = None
if self.has_a:
length_prop = len(self.prop_a)
return length_prop
If I check the typing with mypy:
test.py:10: error: Argument 1 to "len" has incompatible type "Optional[Dict[str, int]]"; expected "Sized"
length_prop = len(self.prop_a)
^
test.py:11: error: Incompatible return value type (got "Optional[int]", expected "int")
return length_prop
Very understandable, since it does not know if self.prop_a is really dict.
How can I design my code to get around this and get the right typing?