2,815 questions
Advice
1
vote
4
replies
69
views
mypy complains about a missing optional module
I have a module (let's name it optional_module) that I want to be imported optionally, as it can be either present or absent. Now I do it this simple way:
try:
import optional_module
except ...
1
vote
0
answers
55
views
Negative narrowing of union type with TypeIs of TypeVar not working as expected in new mypy version
I recently upgraded mypy from 1.17.0 to 1.18.2
The following code was successfully validated in the old mypy version (1.17.0), but fails in the new one (1.18.2):
_T = TypeVar('_T')
class Foo(Generic[...
Best practices
0
votes
3
replies
63
views
Are there any advantages to having mypy check only your entrypoints in your Python program versus every single file?
I'm working with a large, existing Python codebase. Recently someone noticed that one of the files in the testsuite wasn't being type checked by mypy and so suggested to run python -m mypy . rather ...
1
vote
1
answer
97
views
Is there a way to install only stubs (types) and nothing more of a pypi package?
Objective
I'm using mypy to type check my code.
Locally, this works fine by running mypy --install-types once on setup. It installs e.g. scipy-stubs, because the stubs are in an extra package. It ...
-4
votes
1
answer
166
views
How to use type argument as return type?
Is it possible to tell the type checker what the return type is by supplying an input argument, something like rtype here:
from __future__ import annotations
from typing import TypeVar
T = ...
0
votes
0
answers
57
views
How to make Pydantic Generic model type-safe with subclassed data and avoid mypy errors?
I have the following abstract Data class and some concrete subclasses:
import abc
from typing import TypeVar, Generic, Union
from pydantic import BaseModel
T = TypeVar('T')
class Data(BaseModel, abc....
1
vote
0
answers
105
views
How to check source and stub files with mypy?
The Mypy docs state:
If a directory contains both a .py and a .pyi file for the same module, the .pyi file takes precedence. This way you can easily add annotations for a module even if you don’t ...
1
vote
1
answer
125
views
Why does a class attribute named `type` make `type[Foo]` fail?
When I define a class attribute named type, a type[Foo] annotation inside the same class causes mypy to report that the type name is a variable and therefore “not valid as a type”.
class Foo:
type:...
2
votes
0
answers
85
views
Why does the Mediator work with QUERY, but Handler throws an incompatible method override error?
I’m trying to implement a system where I use a Mediator class to execute queries and return results based on the type of QUERY passed. I also want to use a Handler class with a handle method that ...
0
votes
0
answers
69
views
How do I make a Qt5 queued connection in a way that mypy will accept?
Using Python and Qt5, I can make a normal signal connection like this:
def clicked() -> None:
print("clicked")
btn = QtWidgets.QPushButton("Button", window)
btn....
1
vote
1
answer
111
views
Python static code analysis complains about kw argument 'font' in Event.widget.configure
I have a callback
from tkinter import font, ttk
class Foo(ttk.Frame):
def set_font_cb(self, event: tk.Event) -> None:
event.widget.configure(font=font.Font(...))
And this creates in ...
0
votes
0
answers
122
views
structlog enforce Wrapped logger type with mypy
I wanted to override the structlog logger for the whole application, by doing this:
import enum
from collections.abc import Iterable
import structlog
from structlog.typing import Processor
from ...
0
votes
0
answers
73
views
Type hinting for dynamically modified variable type through __setattr__
I am using pydantic with placeholders interpolation in field values:
from typing import Any
from pydantic import BaseModel
class Model(BaseModel):
_placeholders: dict[str, Any]
a: int = "{...
0
votes
1
answer
131
views
Successful mypy run interpreted as failure in pre-commit
Given a .pre-commit-config.yaml:
repos:
- repo: local
hooks:
- id: mypy
name: mypy
language: system
entry: uv run mypy
types: [python]
require_serial: true
exclude: scripts/...
0
votes
0
answers
47
views
Python type hint problem with mixin depending on another
I'm struggling to have the right types in a code implying two related classes and two related mixins, which can be applied on these classes.
Here is the minimal code I have to demonstrate my problem ...
4
votes
2
answers
134
views
Unexpected behavior of mypy with TypeVar, Generic, and decorators
I'm currently in trouble to understand TypeVar and Generic in Python.
Here's the setting of my MWE (Minimal Working Example) :
I defined an abstract class, which has a __call__ method:
This method ...
2
votes
2
answers
131
views
Does mypy not consider "bool(object) == True"?
If Python classes do not define __bool__ or __len__, bool(<class object>) defaults to True.
However, mypy (tested with: v1.15.0) doesn't seem to consider this.
class A:
def __init__(self) -&...
3
votes
1
answer
267
views
Is it possible to define a TypeVar from Generic as an upper bound for another TypeVar?
Let's assume we have the following class hierarchy:
class A:
def a_method(self): ...
class B(A):
def b_method(self): ...
class C(B):
def c_method(self): ...
And a generic ...
4
votes
3
answers
156
views
mypy fails with mixed types in variable length tuple [closed]
mypy fails on code where a variable length tuple contains different types. What should I be doing here?
for i, *s in [(1, 'a'), (2, 'b', 'c')]:
print(hex(i), '_'.join(s))
main.py:2: error: ...
3
votes
1
answer
124
views
Why does mypy issubclass type narrowing only work on "type" instances?
Code snippet:
from typing import Any
class MyClass:
pass
def f(o: Any) -> None:
if isinstance(o, type) and issubclass(o, MyClass):
reveal_type(o) # Revealed type is "Type[...
1
vote
0
answers
59
views
Why is mypy ignoring stub file? [duplicate]
I have the two files in the following directory structure -
.
├── mymod.py
└── mymod.pyi
The files are as follows -
def add(a, b):
return a + b
if __name__ == "__main__":
add(None, ...
0
votes
1
answer
126
views
Mypy: Source file found twice under different module names
https://results.pre-commit.ci/run/github/37489525/1754726473.T4bKKoTUTfG-t4riT2_Kjg
Source file found twice under different module names: "example_scripts.rewrite.src.main" and "testing....
0
votes
0
answers
73
views
Mypy doesn't derive the type from a bounded TypeVar correctly and expect the Parent class
In a generic class with the type constraint by a TypeVar (SomeContext in the MWE) with a bound on an abstract class inheriting from BaseModel (Context in the MWE), mypy doesn't derive the type to all ...
0
votes
0
answers
49
views
How to type annotate a "unique" function? [duplicate]
I want to make a small alias for sorted(list(set(...))). I do:
from typing import Iterable, TypeVar
H = TypeVar("H")
def unique(x: Iterable[H]) -> list[H]:
return sorted(list(set(x))...
1
vote
1
answer
76
views
Mypy error when indexing into array with ellipsis and unpacking
I get a mypy error when I index into an array using both Ellipsis and tuple unpacking.
I have a line of code that looks like this:
new_mat = mat[..., *np.ix_(inds, inds)]
which gives rise to the ...
4
votes
2
answers
187
views
Why isn't dict[str, str] assignable to Mapping[str | int, str] (Mapping key type isn't covariant)?
Given this code:
from collections.abc import Mapping
def my_fn(m: Mapping[str | int, str]):
print(m)
d = {"a": "b"}
my_fn(d)
both mypy 1.16.0 and pyright 1.1.400 report that ...
3
votes
0
answers
153
views
How to avoid repeating type hints when overriding a parent method?
I have this code:
class A:
def f(self, a: int) -> int:
raise NotImplementedError
class B(A):
def f(self, a):
return a
However mypy --strict tells me that B.f "is ...
1
vote
1
answer
78
views
Why does MyPy fail to narrow types when comparing with enum members accessed from another member instead of the class?
Given a simple enumerator:
from enum import Enum
from typing import assert_never
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
And some code that handles members:
a_day = Day(1) ...
2
votes
1
answer
100
views
Why does mypy error on returning list[str, int] + list[int]?
From mypy's point of view l1 + l2 is OK. But returning l1 + l2 isn't OK.
Why?
I'm using Python 3.11 and mypy 1.16.
def test() -> list[str | int]:
l1: list[str | int]
l2: list[int]
l1 + ...
-4
votes
1
answer
227
views
reveal_type in Python as of Python 3.10 in runtime [duplicate]
When using the Mypy playground, this works fine:
def f():
x = 123
reveal_type(x)
However, at run time, it generates the error
NameError: name 'reveal_type' is not defined
I've seen many ...
2
votes
1
answer
123
views
python type annotation of SpecialForms with pydantic and mypy
python 3.13
pydantic 2.10.5
mypy 1.16.0
how to properly annotate return of typing._SpecialForm, specifically typing.Annotated?
I'm using mypy as type checker.
from functools import partial
from ...
5
votes
2
answers
163
views
Containment test against literal list (`y in ["foo", "bar"]`) does not narrow value type
The following MWE causes mypy to error.
from typing import Literal
def expects_literal(x: Literal["foo", "bar"]) -> None:
print(f"{x=}")
def fails_mypy_check(y: ...
-1
votes
1
answer
92
views
How to type-annotate write when subclassing io.RawIOBase, getting "Liskov substitution principle" violation
I want to type-annotate the write in a class that subclasses io.RawIOBase.
I'm struggling to get anything other than Any to type check, which is frustrating, because I should be able to use a much ...
0
votes
1
answer
172
views
Pyright false positive when implementing a protocol [duplicate]
This MRE illustrates my problem:
from dataclasses import dataclass
from typing import Protocol
class Child(Protocol):
val: float
class Parent(Protocol):
sub: Child
@dataclass
class Child1(...
0
votes
1
answer
60
views
mypy type narrowing of a field does not update
I have a test that boils down to:
from enum import Enum
class E(Enum):
A = 1
B = 2
class Test:
def __init__(self) -> None:
self.var = E.A
def update(self, var: E) -> ...
2
votes
1
answer
97
views
mypy linter error (valid-type) with pydantic's Annotated pattern in a generic
Why would the following give a linter error in the second case but not the first:
# OK:
type MyAnnotatedType = Annotated[int | None, Field(strict=True)]
# Error: Invalid type alias: expression is not ...
-2
votes
1
answer
119
views
How do I make mypy treat my class as not being a subtype of object?
I'm trying to write a class in Python where comparisons like MyClass(5) == 5 are considered type errors by mypy, even though in Python all user-defined classes inherit from object.
My goal is to:
...
1
vote
2
answers
183
views
How to get mypy to recognise file `-stubs` package
Here's my folder structure:
.
├── foo
│ ├── __init__.py
│ └── classic.py
├── foo-stubs
│ ├── __init__.pyi
│ └── classic.pyi
├── pyproject.toml
└── t.py
Contents are:
$ cat foo/__init__.py
...
0
votes
0
answers
95
views
Issue while typing a recursive function with list unpacking
I'm trying to correctly type the following function in Python 3.10
from typing import overload
@overload
def joinpath(*path_pieces: str) -> str: ...
@overload
def joinpath(*path_pieces: list[str] |...
1
vote
2
answers
161
views
How to make mypy ignore pytest.approx in a code outside of test functions
I want to use pytest.approx(...) inside immutable dataclasses (frozen=True) in my unittest, so I can use a single assert to check possibly quite complex structures.
This works fine when I use these ...
0
votes
0
answers
93
views
Mypy issue with generics and overload
I'm trying to add types to my code, and I'm running into errors. Below is minimal version of code. I don't understand why B[str] | B[bytes] is incompatible with A[T]. The two last errors are also ...
3
votes
2
answers
210
views
How to type a generic callable in python
I am trying to do something like this:
from collections.abc import Callable, Coroutine
from typing import Any, Generic, TypeVar
CRT = TypeVar("CRT", bound=Any)
class Command(Generic[CRT]): ...
3
votes
1
answer
112
views
How to mark a class as abstract in python (no abstract methods and in a mypy compatible, reusable way)?
I'm trying to make it impossible to instantiate a class directly, without it having any unimplemented abstract methods.
Based on other solutions online, a class should have something along the lines ...
0
votes
1
answer
113
views
Typing sqlalchemy where clauses
Following this doc:
https://docs.sqlalchemy.org/en/20/orm/extensions/mypy.html
I tried to type-check my test.py file:
from sqlalchemy import Column, Integer, String, select
from sqlalchemy.orm import ...
3
votes
1
answer
222
views
Why does all(isinstance(x, str) for x in value) not help Pyright infer Iterable[str] from object?
I'm working with Pyright in strict mode and want to check if a function parameter value of type object is an Iterable[str]. I tried using:
if isinstance(value, Iterable) and all(isinstance(v, str) for ...
-3
votes
1
answer
123
views
Mypy error, [Type] has no attribute [method]
I have an abstract base class:
import abc
import typing as t
class Parent1(abc.ABC):
...
And a subclass of that abstract base class above, that is itself an abstract base class:
class Parent2(...
0
votes
1
answer
82
views
How to write mypy-compatible type hints for injecting `typeguard.check_type` into `typing.cast`
The cast(type, obj) is useful but lack of runtime type checking. Therefore, considering the following code:
from types import GenericAlias, UnionType
from typing import Any, cast
from annotated_types ...
0
votes
0
answers
110
views
Type narrowing using is for TypeVar in generic class
I am working with a generic class in python.
The corresponding TypeVar is restricted to a finite amount of (invariant) types.
Because it is of some importance what exact type it is at runtime, I ...
0
votes
2
answers
134
views
Error type hinting when passing generic class itself as value, did I code something wrong?
I'm trying to create something like a = implemented_class_1 if condition else implemented_class_2 or even dict[key_type, implemented_classes]. But when the implemented_class comes as generic class, ...
3
votes
0
answers
161
views
How to type hint overload Callable and type differently?
How to type hint overload the return type of a Callable and type differently and safely? The problem I'm having is that the type doesn't support ParamSpec, so I can't use that to enforce args and ...