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
14
votes
4 answers

How can I add python type annotations to the flask global context g?

I have a decorator which adds a user onto the flask global context g: class User: def __init__(self, user_data) -> None: self.username: str = user_data["username"] self.email: str = user_data["email"] def login_required(f): …
Chris St Pierre
  • 141
  • 2
  • 4
14
votes
3 answers

How to have inherited type hints in python?

So my problem is That when I have a class of type A that does things and I use those functions as a subclass(B) they are still typed for class A and do not accept my class B object as arguments or as function signature. My problem simplified: from…
user2799096
  • 151
  • 1
  • 1
  • 7
14
votes
1 answer

Get inner type from concrete type associated with a TypeVar

I'm using mypy and the typing module in python. Imagine I have a generic type: ContainerT = TypeVar('ContainerT') class Thingy(Generic[ContainerT]): pass However I want to get at another type inside the concrete type associated with the…
Alexander Kondratskiy
  • 4,156
  • 2
  • 30
  • 51
13
votes
3 answers

mypy and pyproject.toml, options only work globally

I wish to use the options disable_error_code = ["name-defined"] and ignore_missing_imports = true only for some specific modules, but I am struggling to make it work. The following is an excerpt of my non-working pyproject.toml…
Barzi2001
  • 989
  • 8
  • 24
13
votes
1 answer

How to correctly specify type hints with AsyncGenerator and AsyncContextManager

Consider the following code import contextlib import abc import asyncio from typing import AsyncContextManager, AsyncGenerator, AsyncIterator class Base: @abc.abstractmethod async def subscribe(self) ->…
Andreas H.
  • 5,557
  • 23
  • 32
13
votes
1 answer

How to use isinstance on a generic type in Python

I'm trying to check whether an argument is an instance of the generic type specified in the class declaration. However Python does not seem to allow this. T = TypeVar('T') class MyTypeChecker(Generic[T]): def is_right_type(self, x: Any): …
Dax Fohl
  • 10,654
  • 6
  • 46
  • 90
13
votes
2 answers

Python typing: Concatenate sequences

In python, concatenation of two sequences is typically done by the + operator. However, mypy complains about the following: from typing import Sequence def concat1(a: Sequence, b: Sequence) -> Sequence: return a + b And it's right: Sequence…
Ingo
  • 1,103
  • 8
  • 17
13
votes
3 answers

How to hint the type of Django's model field `objects` to a dynamically generated class?

I have a Team model in my Django project. I create its custom model manager with QuerySet.as_manager(). class TeamQuerySet(models.QuerySet): def active(self) -> "models.QuerySet[Team]": return self.filter(is_active=True) class…
viam0Zah
  • 25,949
  • 8
  • 77
  • 100
13
votes
1 answer

Python: Annotate variable as key of a TypedDict

Basically a distilled down version of this (as yet unanswered) question. I want to state that a variable should only take on values that are keys in a TypedDict. At present I'm defining a separate Literal type to represent the keys, for…
SuperShoot
  • 9,880
  • 2
  • 38
  • 55
13
votes
2 answers

How can identical types be incompatible in MyPy?

With the following example: from typing import Callable, Generic, Type, TypeVar XType = TypeVar('XType', bound=int) class C(Generic[XType]): def f(self, x_init: XType) -> XType: return x_init def combinator(c_cls: Type[C[XType]]) ->…
Neil G
  • 32,138
  • 39
  • 156
  • 257
13
votes
1 answer

What is the recommended way to annotate datetime objects?

Suppose I have a function which takes two datetimes and returns the difference in seconds: import datetime def diff(d1: datetime.datetime, d2: datetime.datetime) -> float: return (d2 - d1).total_seconds() if __name__ == '__main__': d1 =…
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
13
votes
2 answers

Is it possible to run mypy pre-commit without making it fail?

I would like to add the following to pre-commit for a team: - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v0.720' hooks: - id: mypy args: [--ignore-missing-imports] My team is worried that this might be too…
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
13
votes
1 answer

Mypy more specific parameter in subclass

I want to declare a base class with an abstract method that has a typed parameter such that implementing classes can specify a more specific type for that parameter, for example: from abc import ABC, abstractmethod class Job(ABC): pass class…
Lukas Schmelzeisen
  • 2,934
  • 4
  • 24
  • 30
13
votes
1 answer

How to make Mypy deal with subclasses in functions as expected

I have the following code: from typing import Callable MyCallable = Callable[[object], int] MyCallableSubclass = Callable[['MyObject'], int] def get_id(obj: object) -> int: return id(obj) def get_id_subclass(obj: 'MyObject') -> int: …
Pro Q
  • 4,391
  • 4
  • 43
  • 92
13
votes
2 answers

Can I suppress mypy errors in-line?

I recently made the mistake of opening my $PYTHONSTARTUP file with mypy syntax checking enabled. As a result, I started getting this error: startup.py|79 col 2 error| Incompatible types in assignment (expression has type "HistoryPrompt", variable…
aghast
  • 14,785
  • 3
  • 24
  • 56