Skip to content
Advertisement

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 might try Union[Dict[str,

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 understand) effectively the same thing; it’s just that BinaryIO is

Python how to type hint a Callable with __wrapped__

When passing around functions, I normally type hint them with typing.Callable. The docs for collections.abc.Callable state that it has four dunder methods: class collections.abc.Callable ABCs for classes that provide respectively the methods __contains__(), __hash__(), __len__(), and __call__(). At one point, I want to check if there is a __wrapped__ attribute on a function. This works fine at runtime via a

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 using the dict keyword to

mypy error: Callable has no attribute “__get__”

I have something like the following: …for which Mypy will return this error: What is the canonical way to specify the type for func, so that Mypy understands it is a descriptor (and thus always has a __get__)? Update: it’s a bit humorous that “descriptor” has no hits when searching the Mypy help. Answer This appears to work fine on

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 import native libraries: On my system CLoader and CDumper aren’t present, which results in the

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 __getitem__ implementation, I have another

Advertisement