Questions tagged [mypy]

Mypy is an optional static type checker for Python.

Mypy is an optional static type checker for Python. Type hints conforming to PEP484 can be added to Python programs using Python's built-in type annotations (since Python 3) or a comment-based annotation syntax for Python 2.

2299 questions
1
vote
1 answer

How to create a type alias with a throw-away generic?

I am looking to create a type alias that can take a generic that is not actually used in the alias. The reason is for self-documenting code, I am aware that no type checker will be able to actually check this. Here is what I mean: from typing import…
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
1
vote
1 answer

typing.Generator extract ReturnType from Generator

taking this properly typed example from the official Python docs: def echo_round() -> Generator[int, float, str]: sent = yield 0 while sent >= 0: sent = yield round(sent) return 'Done' How does one "extract" the ReturnType?…
ThomDietrich
  • 79
  • 1
  • 7
1
vote
1 answer

Call constructor of type parameter in generic class

I'm writing a generic class over AnyStr, so allowing bytes or str. class MyObject(Generic[AnyStr]): ... Inside (multiple) methods of this class, I would like to construct the empty bytes or empty string object, b'' or '', depending on the type…
Michal Charemza
  • 25,940
  • 14
  • 98
  • 165
1
vote
2 answers

How to use None as a placeholder for a non optional variable without mypy complaining about it?

Going straight to the code: from typing import Optional, List class Bar: pass class Foo: def __init__(self, bar_list: List[Optional[Bar]]) -> None: self.bar_list: List[Bar] = bar_list # mypy will signal an error here for…
Janilson
  • 1,042
  • 1
  • 9
  • 23
1
vote
1 answer

Mypy specifying Literal Output

My function returns a tuple of two values, one of which is string with one of two possible values, say "a" or "b". This string is retrieved from the URL and indeed in theory can be something else - in which case I raise a Valuerror. However, it…
Philipp_Kats
  • 3,872
  • 3
  • 27
  • 44
1
vote
0 answers

mypy Error: Unexpected keyword argument for "__init_subclass__"

I just started using mypy to lint my code and I found an error I can't understand, that is similar to this one. I understand the question and it's answer, and it works. Nonetheless,when I split the files and import them I still get the error. Using…
konrad-h
  • 46
  • 9
1
vote
1 answer

Static typing an abstractmethod of an Enum

From abstract super-class enumerations Action and Activity there are the inherited enumerations: ActivityA upon which ActionA can be performed; and ActivityB upon which ActionB can be performed. How can a type declaration be added to the action…
MT0
  • 143,790
  • 11
  • 59
  • 117
1
vote
2 answers

Making Mypy happy about fixed/max-length sequences

In implementation of an interop layer with several other languages I have run into the question of how to represent fixed and max-length sequences. While for Python it doesn't matter much the full type info needs to be available for the other…
1
vote
1 answer

TypeVar confusion, how to type callback functions?

from typing import Tuple, TypeVar, Any ParamArray = TypeVar("ParamArray", Tuple[Any, ...]) The concept is; a ParamArray is just a tuple of values. I have a function def integrate(func, a, b, args=()): delta = 0.1 running_total = 0. for…
Greedo
  • 4,967
  • 2
  • 30
  • 78
1
vote
0 answers

Variable number of types of Generic

I'm struggling with a case where I would like to specify that a class inheriting from typing.Generic can have various number of types. See a following simple example: from typing import * T = TypeVar('T') class C(Generic[T]): data: Tuple[int,…
Drecker
  • 1,215
  • 10
  • 24
1
vote
0 answers

How to properly annotate a generic factory function?

I have the following custom factory function: def converter(cls, data): if isinstance(data, cls): return data else: return cls(**data) After some trial and error, I came across the following solution, which works but seems…
el.atomo
  • 5,200
  • 3
  • 30
  • 28
1
vote
1 answer

Mypy (which runs very slow) raises errors on pandas series methods

Consider the following code: import pandas as pd def calc_mard(x: pd.Series, y: pd.Series) -> float: x_at_y_timestamps: pd.Series = x[y.index] error: pd.Series = y - x_at_y_timestamps mard: float = 100.0 * (error.abs() / x).mean() …
rhz
  • 960
  • 14
  • 29
1
vote
1 answer

How do you get Mypy to enforce invariance, contravariance, and covariance for mutable containers

I'm trying to use typehints and Mypy (also PyCharm) to enforce variance for containers, see, butchered, code below: from typing import TypeVar, Generic class T: ... class M(T): ... class B(M): ... InMT = TypeVar('InMT', bound=M) ContraMT =…
Howard Lovatt
  • 968
  • 1
  • 8
  • 15
1
vote
0 answers

Python: is it possible to infer the possible exceptions that a function can raise?

I was trying to document the possible errors that could occur as a result of a remote procedure call (RPC). It occurred to me that it might be nice if you could do this with a little magic. Is there anything in python to infer possible exceptions…
Att Righ
  • 1,439
  • 1
  • 16
  • 29
1
vote
0 answers

MyPy Decorator that changes output with generics

I'm trying to write a decorator in python that allows any input but change the output as enforced by MyPy. This is as close as I've gotten: Output = TypeVar('Output', bound=pydantic.BaseModel) class Spec(Generic[Output]): # implementation def…
drewag
  • 93,393
  • 28
  • 139
  • 128