4,315 questions
0
votes
1
answer
68
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(...
1
vote
0
answers
65
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
117
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
51
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
104
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
...
1
vote
1
answer
76
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
1
answer
101
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
84
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
108
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
0
answers
99
views
Pydantic model that can take "Any" type?
Say I have a Pydantic model that can take an Any type. If the user sends in JSON on their end, what will Pydantic do here? Will it fail, or will request be of some known type?
Ultimately, I know ...
-4
votes
1
answer
168
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
93
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
115
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[...
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:...
3
votes
0
answers
80
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....
1
vote
1
answer
111
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
216
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
103
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
169
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
113
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
73
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
106
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
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 ...
1
vote
1
answer
142
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
101
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")
...
1
vote
2
answers
118
views
Variadic tuple type parameter
I am trying to annotate a function which receives a tuple of types, and returns a value of one of the provided types.
For example:
@overload
def func[T1](types: tuple[type[T1]]) -> T1: ...
@...
0
votes
0
answers
71
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....
0
votes
0
answers
128
views
telnetlib3, StreamReader/Writer vs. TelnetReader/Writer
I'm trying to type hint my telnetlib3 client.
However, I have some utility code which should not depend on telnet. It should be able to deal with asyncio StreamReader/Writer in common.
Now, if I pass ...
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 ...
1
vote
1
answer
159
views
Type hinting for a generator function that asserts sortedness
I'd like to type-hint a "pass-through" generator that checks for sortedness and raises otherwise:
def assert_sorted(iterable, key=None):
first = True
for item in iterable:
if ...
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 = "{...
5
votes
1
answer
182
views
Python 3.12 Generic syntax and undefined variables
I just stumbled across this weird thing with python 3.12.
I have a type I import under if TYPE_CHECKING:.
When trying to reference this type without quotes, I expect a NameError, because the variable ...
-1
votes
1
answer
59
views
Merging dict with TypedDict casts dict[str,object]?
My goal is to handle multiple functions that are chained and create outputs in dictionaries that are summarized and handed over in a chain. To assert types and that certain keys are present, I am ...
0
votes
1
answer
69
views
How do I implement a Python Protocol with one of two methods? [duplicate]
For example, if I'd need to implement Iterable as a runtime checkable typing.Protocol, I'd implement one that either has __iter__ or both __len__ and __getitem__:
class Iterable[T](Protocol):
def ...
0
votes
1
answer
108
views
Inheriting function type hints from child class
Is there a way to make a generic class A[T], which has a function that inherits the type for the same function in T?
I want to make something like these 2 classes:
class A[T]:
...
def a(self):
...
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 ...
3
votes
1
answer
132
views
Matching on a type hint
I have to interact with an API that returns every result in binary, so I am writing a converter that takes a list of field names and types and converts each returned result to the expected type:
@...
6
votes
2
answers
226
views
Type hint two function parameters to constrain them both to the same type and reject types like numpy.ndarray which do not support boolean comparison
I would like to annotate both parameters of a function – supposed to perform simple comparison between them – in order to indicate that their types should be the same and should support simple ...
0
votes
0
answers
117
views
Python Protocol write-only attributes
The Python documentation on Protocols (typing.Protocol) mentions the following:
By default, protocol variables as defined above are considered readable and writable. To define a read-only protocol ...
1
vote
0
answers
50
views
Static typing for an `Enum` that contains compiled regex patterns
I am in a scenario (that could be compared to writing an AST) where I compile multiple regex patterns that I want to reuse later, and for the sake of simplicity and readability I want to store them in ...
1
vote
0
answers
133
views
How can I type a dict to match a generic `Callable`’s `ParamSpec.kwargs`?
I’m trying to write a small utility that forwards a dict of keyword arguments to an arbitrary callable, and I’d like static type checking to verify that the dict’s keys/values match the callable’s ...
1
vote
1
answer
129
views
Is it possible to set the type of a field based on the value of another field?
I want to set and instantiate the right type based on the value of another field and get typing and autocomplete on it.
I want this to happen automatically when the class is instantiated:
...
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
3
answers
232
views
Type hint empty dict
I need to type-hint that a value is either some TypedDict or a completely empty dict. The TypedDict itself already exists and is non-trivial, and it's an all-or-nothing situation – so modifying the ...
3
votes
2
answers
147
views
Map a generic type to an instance of its type
I have the following inheritance structure:
class S:
...
class A(S):
...
class B(S):
...
I'd like to conceptually do something like the following:
class Foo:
T = TypeVar('T', bound=...
0
votes
1
answer
89
views
How to use type hints in a dict with TypeVar and a function that depends on that TypeVar? [duplicate]
I have a relative simple app in which I use a Message Bus to pass messages.
I prefer a bit more stricter type checking: rather than passing arbitrary text strings as topic, I pass message objects, and ...