Skip to main content
Filter by
Sorted by
Tagged with
3 votes
2 answers
66 views

Mypy triggers the following error: Incompatible return value type (got "tuple[int | None, ...]", expected "tuple[int | None, int | None, int | None, int | None, int | None, int | None, ...
Marcel Wilson's user avatar
2 votes
4 answers
100 views

Let's say I am writing a catalogue of museum items. Let's say I have a data hierarchy like this (all examples below are pseudo code and not taken from any real project): file baseclasses.py class Item:...
BioLogIn's user avatar
0 votes
0 answers
87 views

I have a class that has a member variable that I want to allow to be any container that implements a few functions, which I'm enforcing with the Protocol below: class RandomAccessContainer(Protocol): ...
David McDermott's user avatar
3 votes
2 answers
101 views

In TypeScript I have Omit, constructing a new type from an existing type by removing keys: interface Todo { title: string; description: string; completed: boolean; createdAt: number; } type ...
julaine's user avatar
  • 2,383
2 votes
1 answer
91 views

I'm using inspect.signature() to get a function signature as a string for generating some documentation by hand, and I'm getting a NameError. I have this minimal Python script to reproduce my problem: ...
Raúl Núñez de Arenas Coronado's user avatar
7 votes
1 answer
146 views

I'm currently working on a library that uses dataclasses.dataclass classes for data structures. I'm utilizing the metadata argument of the dataclasses.field() method to inject custom library ...
JackTheFoxOtter's user avatar
1 vote
1 answer
120 views

How do the type alias classes (pseudoclasses?) such as typing.Tuple work? They behave like instance objects since their constructors take arguments But they also behave like class objects: they ...
Jason S's user avatar
  • 191k
2 votes
2 answers
72 views

I am working on a Pyomo model with indexed variables, expressions, and constraints, and I am getting some warnings regarding the ComponentData class. The model still runs smoothly, and the results are ...
Schicko's user avatar
  • 51
1 vote
0 answers
93 views

I have a protocol Store (as described here) that looks like: from typing import Protocol, TypeVar, Any type _KeyT[T] = type[T] T = TypeVar('T', bound='SomeClass') class Store(Protocol): def ...
Bobi's user avatar
  • 39
5 votes
0 answers
107 views

Apologies if there is a straightforward answer already that I'm too smooth brained to see. I am working with Python 3.13+ and Mypy 1.19.1. I've read mypy's docs, read several similar questions/answers ...
Knots's user avatar
  • 51
1 vote
3 answers
144 views

Given: from typing import overload, no_type_check from collections.abc import Mapping @overload def f[K, V](arg: Mapping[K, V], /) -> Mapping[K, V]: ... @overload def f[K, V, V2](arg: Mapping[...
yuri kilochek's user avatar
3 votes
2 answers
207 views

I would like to make __slots__-based classes, without having to repeat the attribute names that I've already listed in type annotations. Before Python 3.14, I could do this: class C: foo: int ...
Dan's user avatar
  • 4,582
3 votes
1 answer
152 views

Implementing a virtual file system I encounter a circular import problem. common.py: from typing import TYPE_CHECKING if TYPE_CHECKING: from .directory import Directory from .archive import ...
big_cat's user avatar
  • 67
2 votes
1 answer
87 views

I am trying to use variadic generics to express the following pattern: given a variadic list of classes, return a tuple of instances whose types correspond positionally to the input classes. ...
Tymon Marek's user avatar
1 vote
0 answers
124 views

When I use a signal's connect method, basedpyright gives a warning. I use the signal as is in the documentation: some_object.someSignal.connect(some_callable). It works, the only problem is the ...
petersohn's user avatar
  • 11.9k
4 votes
1 answer
112 views

I'm trying to hint that a Pydantic BaseModel field needs to be the class tuple or one of its subclasses, so I've typed the field as type[tuple]: from pydantic import BaseModel class Task1(BaseModel): ...
bin9980's user avatar
  • 71
3 votes
1 answer
99 views

In order to narrow type into literal types, I usually do the following: from typing import Literal, TypeIs, get_args, reveal_type type OneTwoThree = Literal[1, 2, 3] type FourFiveSix = Literal[4, 5, ...
Leonardus Chen's user avatar
2 votes
1 answer
111 views

I struggle with typechecks using matplotlib.pyplot.subplot_mosaic. I have create the following fuction, which generates the mosaic pattern and the per_subplot_kw: def create_mosaic(num_rows): def ...
MaKaNu's user avatar
  • 1,108
0 votes
1 answer
107 views

How to type libraries using ahk? I thought about doing it like this: class AHKMouseController: def __init__( self, ahk: AHK ): self._ahk = ahk But mypy complains: ...
AsfhtgkDavid's user avatar
Best practices
2 votes
2 replies
135 views

I am working with an application that uses Pydantic models extensively. Many attributes on these models are set to Optional but with a default value to ensure that they are not None. The intent is ...
Tim Pierce's user avatar
  • 5,724
1 vote
1 answer
128 views

I'm using basedpyright for static type checking, and it fails to resolve imports from a test utility module located under the tests directory. However, unittest executes the tests without any issues. ...
usan's user avatar
  • 179
3 votes
2 answers
135 views

I'm overloading a method so the return type differs depending on the value of a given bool parameter. That same parameter has a default value (False in my case). Here's a simplistic example function ...
chrsmrrtt's user avatar
  • 329
Best practices
0 votes
1 replies
43 views

I'm building a simulation engine in Python and want to use generics so that events are strongly typed to a simulation state. I have something like this: from __future__ import annotations from abc ...
Davis Cotton's user avatar
3 votes
1 answer
102 views

Pyright type inference seems unable to convert unions of homogeneous sequences, e.g. from Union[tuple[A, ...], tuple[B, ...]] to Union[list[A], list[B]]. Suppose a function which takes as input an ...
Vexx23's user avatar
  • 203
0 votes
1 answer
103 views

I have a setup like the following from typing import Generic, TypeVar T = TypeVar("T") class ThirdParty: def __init_subclass__(cls): ... # does not call super() class Mine(...
Daraan's user avatar
  • 5,245
3 votes
1 answer
140 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,126
2 votes
2 answers
152 views

We use pyre for linting and have been updating some old polymorphic code to be typed. The __init__ method has quite a few arguments and was using **kwargs to pass them through the various layers with ...
tsuckow's user avatar
  • 21
1 vote
1 answer
59 views

I have a test that has code that executes a workflow which PyCharm marks as incorrect (pyright doesn't complain) result = await workflow_client.execute_workflow( SayHelloWorkflow.run, req, id=&...
Archimedes Trajano's user avatar
2 votes
0 answers
121 views

I have classes like this: class TensorLike(ABC): @property @abstractmethod def conj(self) -> 'TensorLike': ... class Tensor(TensorLike): _conj: 'Conjugate|None'=None @property ...
ATP's user avatar
  • 20
2 votes
1 answer
288 views

I am currently defining ORMs and DTOs in my fastapi application, and using SQLAlchemy 2.0 for this job. Many sources, including the official docs, specify that the way to use mapped types with ORMs is ...
xxixx's user avatar
  • 21
1 vote
2 answers
291 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,327
1 vote
0 answers
131 views

TL;DR Suppose a Python library defines an interface meant to be implemented by third-party code. How could this library provide a factory function that creates instances of those implementations, with ...
mgab's user avatar
  • 4,064
2 votes
1 answer
129 views

I'm trying to create a function dynamically. Here is an example: import ast import textwrap from typing import Any, Callable, List, Union def create_function( func_name: str, arg_types: List[...
Danila Ganchar's user avatar
-4 votes
1 answer
192 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,676
0 votes
1 answer
110 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
136 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
109 views

Python 3.12 introduced new syntax sugar for generics. What's the new way of writing an upper-bounded generic like this: def foo[T extends Bar](baz: T) -> T: ... Before new syntax features I ...
detectivekaktus's user avatar
1 vote
1 answer
125 views

I'm using PyRight, and (until now), I've been happily instructing students to create lists using "multiplication", e.g. 44 * [None]. However, when the resulting list is of type, say, List[...
John Clements's user avatar
2 votes
0 answers
139 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,767
3 votes
0 answers
92 views

I have code: import logging from typing import Generic, TypeVar from typing import Self, Any, Type from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session logger = logging....
Альберт Александров's user avatar
0 votes
1 answer
172 views

I want to annotate a type parameter for a generic dataclass of mine with a Google style docstring to both support generating documentation and mouse hovering within VS Code (and other editors/IDEs). ...
Snap's user avatar
  • 878
Tooling
6 votes
3 replies
226 views

Python type hints have evolved remarkably across versions, for example from Union[str, List[str]] to str | list[str]. I know that both are valid, but the team and I find the newer more readable. Is ...
C. Claudio's user avatar
0 votes
1 answer
127 views

I'm trying to type hint my fastAPI to take both a BaseModel pydantic class for various arguments and some seperate files. I also want to add a description for all of the inputs on http://127.0.0.1:...
Felix's user avatar
  • 1
6 votes
1 answer
182 views

The following code-snippet bridges some dataclasses and GUI-classes using PySide6 (the Qt library). The HasDataobject class is key here. It defines a mix-in for subclasses of QGraphicsItem. It adds an ...
MacFreek's user avatar
  • 3,586
1 vote
2 answers
116 views

Preamble I'm using polars's write_excel method which has a parameter column_formats which wants a ColumnFormatDict that is defined here and below ColumnFormatDict: TypeAlias = Mapping[ # dict of ...
Dean MacGregor's user avatar
0 votes
1 answer
93 views

I'm using a field wrap validator in Pydantic with the Annotated pattern, and I want to access the expected/annotated type of a field from within the validator function. Here's an example of what I ...
kviLL's user avatar
  • 455
4 votes
0 answers
131 views

I want to narrow an unambiguously defined dict[...] type in a superclass to a specific TypedDict in an inheriting class but I cannot figure out a way to specify a dict-based supertype that the ...
bossi's user avatar
  • 1,744
2 votes
0 answers
89 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
1 vote
1 answer
144 views

How can I implement DecoratorFactory such that it type-checks as follows: def accepts_foo(foo: int): ... def accepts_bar(bar: int): ... decorator_foo = DecoratorFactory(foo=1) decorator_foo(...
obk's user avatar
  • 856
1 vote
1 answer
102 views

I want to make a database agent that has multiple calls in separate classes. Here is a simplified example of what I want to do: from typing import Any, Generic, ParamSpec P = ParamSpec("P") ...
L1RG0's user avatar
  • 31

1
2 3 4 5
87