Skip to content

Tag: mypy

Stronger type-annotation for a mixed-type mapping

Suppose I have a mapping that maps string -> int, and int -> string in one dictionary. Is there a way to express that with type annotations in a strict way? Currently I can do Dict[Union[str, int], Union[str, int]], but that allows for str -> str, and int -> int, which I do not actually want. One …

mypy declares IO[bytes] incompatible with BinaryIO

Consider the following code: Running mypy v0.782 on the above code under Python 3.6.9 fails with the following error: However, I feel that this code should not be regarded as an error, as ZipFile.open() returns a binary filehandle, which TextIOWrapper accepts. Moreover, IO[bytes] and BinaryIO are (as far as I…

Static type analysis with Python dicts

Can someone explain why this code, while valid, makes the mypy static analyser complain in multiple ways: Namely: If I simply add a type hint to the initial variable of ranges: dict = dict() it works fine. I am confused about why the static analyser can’t work this out by itself, especially as I am usin…

How can mypy ignore a single line in a source file?

I’m using mypy in my python project for type checking. I’m also using PyYAML for reading and writing the project configuration files. Unfortunately, when using the recommended import mechanism from the PyYAML documentation this generates a spurious error in a try/except clause that attempts to imp…

Subclassing Sequence with proper type hints in Python

I’m trying to implement a kind of custom sequence class in Python: Now I want to check that mypy is aware that elements of MySequence are items of type T: So it fails: mypy knows nothing about items of foo. The same example for ordinary Sequence works: If I’m trying to add type annotations to __ge…