I am new to Python's static typing module mypy. I am trying to append ints and floats to an array, which I typed statically to be Real. But mypy says that they are incompatible types with Real. I thought ints and floats are a subtype of Real?
from typing import List
from numbers import Real
data : List[Real] = []
with open(path, 'r') as file:
for line in file:
line = line.strip()
if subject == 'time':
data.append(float(line))
else:
data.append(int(line))
Error message:
graph.py:56: error: Argument 1 to "append" of "list" has incompatible type "float"; expected "Real"
graph.py:58: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "Real"
As AChampion says you can just use float in place of numbers.Real. Pep 0484 (specifically here) basically says that in the context of type-checking the hierarchy complex > float > int is respected and that numbers.* doesn't need to be used.
This is a known 'issue' with mypy and was raised and discussed here. I haven't read the entire discussion but the tldr seems to be that Pep 0484 is enough to make this a low priority issue (and it hasn't been resolved in 5 years).
I will say that (as the issue discussion mentioned) it would be nice if mypy gave some indication of this as a known issue in it's error message, which it currently (mypy 0.991) doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With