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
12
votes
1 answer

Get mypy to accept subtype of generic type as a method argument

I'm trying to extract a pattern that we are using in our code base into a more generic, reusable construct. However, I can't seem to get the generic type annotations to work with mypy. Here's what I got: from abc import ( ABC, …
Christoph
  • 26,519
  • 28
  • 95
  • 133
12
votes
1 answer

type hint: how should type of lru_cache be defined?

Given the following function @lru_cache(maxsize=1) def get_response_from_api() -> List[ApiObject]: url = _get_api_url() response = requests.get(url).text return json.loads(response, object_hook=_create_api_obj) when running mypy…
David Michael Gang
  • 7,107
  • 8
  • 53
  • 98
12
votes
1 answer

Flake 8: "multiple statements on one line (colon)" only for variable name starting with "if"

I'm using flake8 in Visual Studio Code, writing some code using Python 3.6 variable annotations. It worked without any problems so far, but I encountered a strange warning. This works fine: style: str = """ width: 100%; ... """ # Doing sth with…
linusg
  • 6,289
  • 4
  • 28
  • 78
12
votes
4 answers

Trying to add mypy into PyCharm

Trying to setup mypy with my PyCharm Professional 2017.2. But it doesn't work. I also would like to setup mypy check on one particular file vs entire project, can some please share the way they have configured mypy in their PyCharm.
yadayada
  • 327
  • 1
  • 3
  • 14
12
votes
1 answer

mypy error - incompatible type despite using 'Union'

Consider following code sample: from typing import Dict, Union def count_chars(string) -> Dict[str, Union[str, bool, int]]: result = {} # type: Dict[str, Union[str, bool, int]] if isinstance(string, str) is False: …
Jan Rozycki
  • 1,603
  • 2
  • 15
  • 19
12
votes
1 answer

mypy spurious error: "module" has no attribute "XPath" with etree

I'm trying to use mypy to do type checking in some code that uses the LXML library to parse XML. On each line where I use etree.XPath, I get a spurious error from mypy. For example, the following trivial script from lxml import etree NameXPath…
uglycoyote
  • 1,555
  • 1
  • 19
  • 25
11
votes
2 answers

Python typing: Does TypedDict allow additional / extra keys?

Does typing.TypedDict allow extra keys? Does a value pass the typechecker, if it has keys which are not present on the definition of the TypedDict?
Jonathan Scholbach
  • 4,925
  • 3
  • 23
  • 44
11
votes
1 answer

How to annotate the type of arguments forwarded to another function?

Let's say we have a trivial function that calls open() but with a fixed argument: def open_for_writing(*args, **kwargs): kwargs['mode'] = 'w' return open(*args, **kwargs) If I now try to call open_for_writing(some_fake_arg = 123), no type…
Migwell
  • 18,631
  • 21
  • 91
  • 160
11
votes
2 answers

How to alias generic types for decorators

Consider the example of a typed decorator bound to certain classes. import unittest from typing import * T = TypeVar("T", bound=unittest.TestCase) def decorate(func: Callable[[T], None]) -> Callable[[T], None]: def decorated_function(self: T)…
Zulan
  • 21,896
  • 6
  • 49
  • 109
11
votes
3 answers

How to resolve mypy error with sqlalchemy enum?

mypy reports an error in the following code: import enum from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Enum Base = declarative_base() class MyEnum(enum.Enum): A = 1 B = 2 class MyTable(Base): …
Rahul
  • 963
  • 9
  • 14
11
votes
1 answer

Initialize a TypedDict and fill keys & values later

I have a dict with of which the types of the keys and values are fixed. I want to define the types in a TypedDict as follows: class MyTable(TypedDict): caption: List[str] header: List[str] table: pd.DataFrame epilogue: List[str] I…
MaartenB
  • 383
  • 1
  • 2
  • 12
11
votes
1 answer

Nice way to turn a dict into a TypedDict?

Note: since this answer keeps getting upvoted - while there are still use cases for TypedDict, I'd consider using a dataclass instead today. I want to have a nice (`mypy --strict` and pythonic) way to turn an untyped `dict` (from `json.loads()`)…
frans
  • 8,868
  • 11
  • 58
  • 132
11
votes
2 answers

Generate TypedDict from function's keyword arguments

foo.py: kwargs = {"a": 1, "b": "c"} def consume(*, a: int, b: str) -> None: pass consume(**kwargs) mypy foo.py: error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "int" error: Argument 1 to "consume" has…
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
11
votes
1 answer

Mypy: How should I type a dict that has strings as keys and the values can be either strings or lists of strings?

I am using Python 3.8.1 and mypy 0.782. I don't understand why mypy complains about the following code: from typing import Union, List, Dict Mytype = Union[Dict[str, str], Dict[str, List[str]]] s: Mytype = {"x": "y", "a": ["b"]} Mypy gives the…
jjei
  • 1,180
  • 3
  • 13
  • 21
11
votes
2 answers

Typechecking dynamically added attributes

When writing project-specific pytest plugins, I often find the Config object useful to attach my own properties. Example: from _pytest.config import Config def pytest_configure(config: Config) -> None: config.fizz = "buzz" def…
hoefling
  • 59,418
  • 12
  • 147
  • 194