4,324 questions
3
votes
2
answers
66
views
Getting mypy to recognize tuple of certain length
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, ...
2
votes
4
answers
100
views
Proper python type-hinting for functions that return a list of objects of unknown classes
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:...
0
votes
0
answers
87
views
How to implement a Protocol as a class instance variable?
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):
...
3
votes
2
answers
101
views
Is there a Python equivalent of TypeScript's Omit?
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 ...
2
votes
1
answer
91
views
`NameError` from `inspect.signature()` or `obj.__annotations__` for types present only in `TYPE_CHECKING` block
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:
...
7
votes
1
answer
146
views
How to annotate a function that returns a dataclass field so that type checkers treat it correctly?
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 ...
1
vote
1
answer
120
views
How do type aliases (typing.Tuple, typing.Set, typing.List, etc.) work as an instance but also a class?
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 ...
2
votes
2
answers
72
views
Why does the PyCharm type checker give a warning about operators in the ComponentData class when they are indexed?
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 ...
1
vote
0
answers
93
views
How to type dict_keys/items/values in Python? [duplicate]
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 ...
5
votes
0
answers
107
views
Can someone help explain Python's mypy issue with Incompatible return value type due to covariance when returning a sub type of a union
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 ...
1
vote
3
answers
144
views
typing.overload based on presence of keyword arguments
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[...
3
votes
2
answers
207
views
How to generate __slots__ based on annotations in Python 3.8-3.14
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
...
3
votes
1
answer
152
views
How do I resolve this circular import?
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 ...
2
votes
1
answer
87
views
Map variadic generics to their class equivalent
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.
...
1
vote
0
answers
124
views
basedpyright gives 'Type of "connect" is partially unknown' on PyQt6 connect
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 ...
4
votes
1
answer
112
views
How to type hint class tuple itself not instance without pylance complaining
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):
...
3
votes
1
answer
99
views
How to narrow type of literals using generics?
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, ...
2
votes
1
answer
111
views
Why is list[list[str]] not equal to list[HashableList[Hashable]]
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 ...
0
votes
1
answer
107
views
How to type libraries using ahk? [duplicate]
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:
...
Best practices
2
votes
2
replies
135
views
how to enforce not-None for Optional arguments to Pydantic models
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 ...
1
vote
1
answer
128
views
basedpyright cannot resolve imports from tests directory even though unittest run fine
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. ...
3
votes
2
answers
135
views
VS Code selects incorrect overload when a function parameter has a default value
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 ...
Best practices
0
votes
1
replies
43
views
How to type a generic SimulationEvent and engine in Python without “TypeVar bound type cannot be generic” errors?
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 ...
3
votes
1
answer
102
views
Propagate correctly unions across containers with pyright
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 ...
0
votes
1
answer
103
views
Subclass of Generic fails with AttributeError: object has no attribute '__parameters__' - using Generic when superclass does forward __init_subclass__
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(...
3
votes
1
answer
140
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[...
2
votes
2
answers
152
views
Enforce __init__ method's arguments are superset of base class
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 ...
1
vote
1
answer
59
views
How do I get around a typing issue for execute_workflow in PyCharm
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=&...
2
votes
0
answers
121
views
How to annotate with the generic type of self?
I have classes like this:
class TensorLike(ABC):
@property
@abstractmethod
def conj(self) -> 'TensorLike': ...
class Tensor(TensorLike):
_conj: 'Conjugate|None'=None
@property
...
2
votes
1
answer
288
views
Sqlalchemy mapped_column typing issues with pylance
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 ...
1
vote
2
answers
291
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 ...
1
vote
0
answers
131
views
How to provide type-safe factory functions for dynamically registered classes in Python?
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 ...
2
votes
1
answer
129
views
Type checker highlights 'Unexpected argument' for dynamically generated function
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[...
-4
votes
1
answer
192
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
1
answer
110
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
136
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
109
views
Python 3.12+ generic syntax for <T extends Foo>
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 ...
1
vote
1
answer
125
views
Is it possible to create lists of a union type using the multiplication operator?
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[...
2
votes
0
answers
139
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:...
3
votes
0
answers
92
views
How to resolve error Unresolved attribute reference 'create' for class 'BaseRepository'
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....
0
votes
1
answer
172
views
Python Google style doc string for generic class Type Parameter
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). ...
Tooling
6
votes
3
replies
226
views
Automatic Python type hint migration
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 ...
0
votes
1
answer
127
views
Combining Pydantic Models and File Uploads
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:...
6
votes
1
answer
182
views
Type-hinting a combined Mix-in class and subclass leads to TypeErrors
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 ...
1
vote
2
answers
116
views
python typing distinctions between inline created parameters and variables
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 ...
0
votes
1
answer
93
views
Access expected type in Pydantic within a field wrap validator using the annotated pattern
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 ...
4
votes
0
answers
131
views
Narrowing dict to TypedDict
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 ...
2
votes
0
answers
89
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 ...
1
vote
1
answer
144
views
Type hint a decorator to enforce matching signature as the decorated function
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(...
1
vote
1
answer
102
views
How to make a python typechecker point to a correct function signature
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")
...