When I use a dict where members have different types, mypy accepts my type definitions within the class but not outside.
The access of member 'first' in
ExampleClass.__str__()
does not produce an error from mypy when I iterate over it.
But when I get same data outside the class, iterating over 'first' causes mypy to generate an error.
What is going on?
from typing import Union, List, Dict
from collections import namedtuple
class ExampleClass:
PrimeOption = namedtuple('PrimeOption', ['value1', 'value2'])
PrimeList = List[PrimeOption]
ExampleData = Dict[str, Union[bool, PrimeOption]]
def __init__(self):
self.data:ExampleData = {'flag':False,
'first': [ExampleClass.PrimeOption.value1]}
def get(self) -> ExampleData:
return self.data
def __str__(self):
t = self.get()
out = 'ExampleClass:'
for i in t['first']:
out += str(i)
return out
if __name__ == "__main__":
obj = ExampleClass()
print(obj)
t = obj.get()
for i in t['first']:
print(i)
This produces one error from mypy:
$ mypy union.py union.py:33: error: Item "bool" of "Union[bool, PrimeOption]" has no attribute "__iter__" (not iterable) Found 1 error in 1 file (checked 1 source file)
I am using python3.8.8 and mypy 0.812.
Edit: This needs to work with python3.6.