Skip to main content
Filter by
Sorted by
Tagged with
Advice
1 vote
4 replies
69 views

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 ...
Phant's user avatar
  • 43
1 vote
0 answers
55 views

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[...
Georg Plaz's user avatar
  • 6,028
Best practices
0 votes
3 replies
63 views

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 ...
Newbyte's user avatar
  • 3,957
1 vote
1 answer
97 views

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 ...
Mo_'s user avatar
  • 2,080
-4 votes
1 answer
166 views

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 = ...
Moberg's user avatar
  • 5,646
0 votes
0 answers
57 views

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....
Relys's user avatar
  • 85
1 vote
0 answers
105 views

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 ...
lupl's user avatar
  • 974
1 vote
1 answer
125 views

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:...
J Kluseczka's user avatar
  • 1,757
2 votes
0 answers
85 views

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 ...
Aleksey's user avatar
  • 33
0 votes
0 answers
69 views

Using Python and Qt5, I can make a normal signal connection like this: def clicked() -> None: print("clicked") btn = QtWidgets.QPushButton("Button", window) btn....
Scott McPeak's user avatar
  • 13.8k
1 vote
1 answer
111 views

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 ...
fsdfsdfsdfsdfsdf's user avatar
0 votes
0 answers
122 views

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 ...
comonadd's user avatar
  • 2,018
0 votes
0 answers
73 views

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 = "{...
maejam's user avatar
  • 1
0 votes
1 answer
131 views

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/...
Seanny123's user avatar
  • 9,446
0 votes
0 answers
47 views

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 ...
fabien-michel's user avatar
4 votes
2 answers
134 views

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 ...
python_is_superbe's user avatar
2 votes
2 answers
131 views

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) -&...
matheburg's user avatar
  • 2,201
3 votes
1 answer
267 views

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 ...
Gygabrain's user avatar
  • 101
4 votes
3 answers
156 views

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: ...
grahamstratton's user avatar
3 votes
1 answer
124 views

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[...
Leonardus Chen's user avatar
1 vote
0 answers
59 views

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, ...
tinkerbeast's user avatar
  • 2,107
0 votes
1 answer
126 views

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....
Irina's user avatar
  • 1,417
0 votes
0 answers
73 views

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 ...
Nitsugua's user avatar
0 votes
0 answers
49 views

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))...
KamilCuk's user avatar
  • 146k
1 vote
1 answer
76 views

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 ...
aklmn's user avatar
  • 31
4 votes
2 answers
187 views

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 ...
Kerrick Staley's user avatar
3 votes
0 answers
153 views

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 ...
bfontaine's user avatar
  • 21.3k
1 vote
1 answer
78 views

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) ...
Rylix's user avatar
  • 13
2 votes
1 answer
100 views

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 + ...
Stas Stepanov's user avatar
-4 votes
1 answer
227 views

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 ...
Max Koretskyi's user avatar
2 votes
1 answer
123 views

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 ...
Alexander Konukhov's user avatar
5 votes
2 answers
163 views

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: ...
scnlf's user avatar
  • 74
-1 votes
1 answer
92 views

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 ...
Cornelius Roemer's user avatar
0 votes
1 answer
172 views

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(...
Durtal's user avatar
  • 1,108
0 votes
1 answer
60 views

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) -> ...
user14590978's user avatar
2 votes
1 answer
97 views

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 ...
qix's user avatar
  • 8,064
-2 votes
1 answer
119 views

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: ...
Филя Усков's user avatar
1 vote
2 answers
183 views

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 ...
ignoring_gravity's user avatar
0 votes
0 answers
95 views

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] |...
Marco Bresson's user avatar
1 vote
2 answers
161 views

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 ...
Jan Spurny's user avatar
  • 5,597
0 votes
0 answers
93 views

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 ...
Skyman2413's user avatar
3 votes
2 answers
210 views

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]): ...
niltz's user avatar
  • 1,178
3 votes
1 answer
112 views

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 ...
Sam Coutteau's user avatar
0 votes
1 answer
113 views

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 ...
sevan's user avatar
  • 3,974
3 votes
1 answer
222 views

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 ...
Yamin Maazou's user avatar
-3 votes
1 answer
123 views

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(...
Harianja Lundu's user avatar
0 votes
1 answer
82 views

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 ...
Tsukimaru Oshawott's user avatar
0 votes
0 answers
110 views

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 ...
502E532E's user avatar
  • 581
0 votes
2 answers
134 views

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, ...
LibrarristShalinward's user avatar
3 votes
0 answers
161 views

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 ...
Nelson Yeung's user avatar
  • 3,472

1
2 3 4 5
57