mypy

Python typing for a metaclass Singleton

Python typing for a metaclass Singleton Question: I have a Python (3.8) metaclass for a singleton as seen here I’ve tried to add typings like so: from typing import Dict, Any, TypeVar, Type _T = TypeVar("_T", bound="Singleton") class Singleton(type): _instances: Dict[Any, _T] = {} def __call__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: if cls …

Total answers: 1

Type hint for numpy.ndarray containing unsignedinteger

Type hint for numpy.ndarray containing unsignedinteger Question: I have a numpy array that contains unsignedinteger, something like this: arr = np.uint16([5, 100, 2000]) array([ 5, 100, 2000], dtype=uint16) This arr will be input to a function. I am wondering how the type hint of the function argument should look like? def myfunc(arr: ?): pass I …

Total answers: 2

Python type hints for unpacking object

Python type hints for unpacking object Question: I’m trying to implement type hinting for object unpacking. Here is what I have currently from typing import Tuple class A: def __init__(self, x: int, y: str): self.x = x self.y = y def astuple(self) -> Tuple[int, str]: return self.x, self.y # Need to annotate the return type …

Total answers: 1

Type checking a method call with a default argument prior to keyword argument dictionary

Type checking a method call with a default argument prior to keyword argument dictionary Question: Given def f_with_opt(opt_arg: bool | None = None, **kwargs): print(f"{opt_arg=}, {kwargs=}") def function() -> None: kwargs = {"foo": "bar"} f_with_opt(**kwargs) # mypy complains about this line if __name__ == "__main__": function() mypy reports test.py:7:18: error: Argument 1 to "f_with_opt" has …

Total answers: 2

Ignoring mypy attr-defined with triple quotes

Ignoring mypy attr-defined with triple quotes Question: The following code: # type: ignore[attr-defined] timeit.template = """ # type: ignore[attr-defined] def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: retval = {stmt} _t1 = _timer() return _t1 – _t0, retval """ # type: ignore[attr-defined] # type: ignore[attr-defined] Yields error: src/snncompare/Experiment_runner.py:45: error: Module has no …

Total answers: 1

mypy: error: Module "multiprocessing.managers" has no attribute "EventProxy" [attr-defined]

mypy: error: Module "multiprocessing.managers" has no attribute "EventProxy" [attr-defined] Question: I have a method which takes a multiprocessing.Manager().Event(), for the purposes of gracefully stopping my app. When I run mypy against it, it complains that it’s not a valid type: error: Module "multiprocessing.managers" has no attribute "EventProxy" [attr-defined] Code: from multiprocessing.managers import EventProxy class App: …

Total answers: 1

mypy seems to think that (*args, **kwargs) could match to any funtion signature?

mypy seems to think that (*args, **kwargs) could match to any funtion signature? Question: How does mypy apply the Liskov substitution principle to *args, **kwargs parameters? I thought the following code should fail a mypy check since some calls to f allowed by the Base class are not allowed by C, but it actually passed. …

Total answers: 2

Annotating function with TypeVar and default value results in union type

Annotating function with TypeVar and default value results in union type Question: When annotating a function parameter with a bound TypeVar, giving it a default value results in the parameter having a union type between the TypeVar and the default value type, even though the default value is of the TypeVar type. Example: class A: …

Total answers: 1

How to check that a string is a string literal for mypy?

How to check that a string is a string literal for mypy? Question: With this code import os from typing import Literal, get_args Markets = Literal[ "BE", "DE", "DK", "EE", "ES", "FI", "FR", "GB", "IT", "LT", "LV", "NL", "NO", "PL", "PT", "SE" ] MARKETS: list[Markets] = list(get_args(Markets)) def foo(x: Markets) -> None: print(x) market = …

Total answers: 2

mypy – Type-hint new attributes

mypy – Type-hint new attributes Question: I often use dict to group and namespace related data. Two drawbacks are: I cannot type-hint individual entries (e.g. x[‘s’]: str = ”). Accessing union-typed values (e.g. x: dict[str, str | None] = {}) later needs assert statements to please mypy. Spelling entries is verbose. Values mapped to str …

Total answers: 1