Questions tagged [python-typing]
For questions related to PEP 484 (Type Hints), PEP 526 (Syntax for Variable Annotations) and the `typing` module.
1,930
questions
0
votes
1
answer
38
views
python 3.12 typing override function
this type of defining function in python looks a little bit weird to me
def override[F: type](method: F, /) -> F:...
what is the meaning of [F: type] exactly?
is it something like, new way of ...
1
vote
1
answer
28
views
How can I have an optional TypeVar in a Generic class in Python?
I'm trying to write a simple type wrapper to represent the interface of decorator functions:
from typing import Protocol, TypeVar, Generic
TIn = TypeVar('TIn', contravariant=True)
TOut = TypeVar('...
0
votes
1
answer
82
views
How to precisely describe a dict type?
I am back to Python (after some infidelities with Go and Typescript) and in the meantime the type parameter landed in.
I tried to understand how to use it to precisely describe a dict structure, but ...
0
votes
2
answers
38
views
How to resolve mypy errors when changing values with a Literal type?
I need to change the value of an attribute that has a Literal type.
In a real case, I have a long list of values in ValidChar and I need to convert it to List[str] for checking.
mypy shows an error ...
0
votes
0
answers
35
views
mypy incompatible return type in overriden method
I am subclassing UserDict class in python 3.11, and I intend to override the __or__ method,
When trying to do it, mypy claims that I am using an incompatible return type.
Here's an example code to ...
0
votes
1
answer
33
views
How do I create a generic for an unknown number of argument of a Callable in python?
In this programming exercise, I wrote a starmap generator as an equivalent to itertools.starmap and aimed to provide accurate type hints. The code snippet below showcases the implementation:
from ...
2
votes
1
answer
55
views
Handle circular import of subclasses types in abstract class
I am facing a circular import error when I define type aliases for the subclasses of an abstract class.
This is an example of what I'm trying to achieve:
#abstract_file_builder.py
from abc import ABC,...
10
votes
0
answers
295
views
Python type hints for type promotion
Consider a function that performs type promotion, e.g. a simple multiplication of two numbers that can both be either int or float:
def mul(a: int | float, b: int | float): # return type?
return ...
-2
votes
0
answers
28
views
How to Organize Python Methods for Typing and Documentation in an ffmpeg Wrapper with Many Filters [closed]
I'm currently working on adding typing support and documentation to a Python ffmpeg wrapper, allowing users to write ffmpeg filters in Python with autocomplete, type hints and proper documentation. I'...
-1
votes
2
answers
51
views
How to get fastapi type conversion str->bool?
I have external service. It call my api with get parameters
class Misc(BaseModel):
# - whether to pop-up checkbox ("true" or "false")
popup: Optional[str] = None
# - ...
-1
votes
0
answers
21
views
python datetime typing hints for a specific format
I have a class whose constructor takes a datetime object. What is the correct way to specify the hint that the datetime must be in the yyyy-MM-dd hh:mm:ss format?
i am on python3.10
2
votes
2
answers
105
views
In Python typing is there a way to specify combinations of allowed generic types that are dependent?
I have a pretty small but versatile (maybe too much) class in Python that effectively has two generic types that are constrained together. My code (yet poorly typed) code should show my intent:
class ...
0
votes
0
answers
51
views
Pyright ... (triple dot) is not allowed in this context [duplicate]
I am on python 3.11 and i am using type hints for annotations. I have a function parameter which takes list of any length, all elements should of type str, for this when I do the following:
def ...
0
votes
1
answer
48
views
How to add python type check for a Callable with a defined argument and kwargs
What I have is a function as a parameter. This function will always need to take a dictionary, and then can optionally take any number of keyword arguments. See code below for a simplified example:
...
1
vote
1
answer
39
views
Is multiprocessing.Queue generic or not (pyright)?
I started using pyright recently (over mypy) and it's finding a lot of issues that weren't coming up with mypy. For example
from multiprocessing import Queue
queue: Queue = Queue() # Type of "...
1
vote
2
answers
115
views
How can I type annotate a decorator that takes optional arguments?
Let's say I define a decorator like this:
def my_decorator(func=None, *, param=42):
if func is None:
return functools.partial(my_decorator, param=param)
...
This decorator can be used ...
0
votes
1
answer
43
views
Typing/completion in a generic container
Imagine this setup, where I define a generic container, with as goal to make it easy to search inside:
from typing import Any, Generic, Self, TypeVar
from pydantic import BaseModel
T = TypeVar("...
1
vote
1
answer
87
views
How can mutable variables be treated as "volatile" for static type checking?
Consider this class which has a variable state that is compared twice in the method check_twice and its value is changed in between the two checks by the method work:
import enum
class State(enum....
0
votes
0
answers
105
views
What is the best way to use typing and Python 3.x?
So, I have recently started playing around with OpenAI, however, when installing and importing the library I have faced such an issue:
ImportError: cannot import name 'Required' from 'typing' (/...
2
votes
3
answers
121
views
Infer return type annotation from other function's annotation
I have a function with a complex return type annotation:
from typing import (Union, List)
# The -> Union[…] is actually longer than this example:
def parse(what: str) -> Union[None, int, bool, ...
4
votes
0
answers
83
views
Python Type Narrowing with TypeGuard: Narrowing Return type that is a TypeVar
Consider the following case:
from typing import Union, TypeVar, List
from typing_extensions import TypeGuard
_T = TypeVar('_T', str, int)
def is_str(val: _T) -> TypeGuard[str]:
return ...
2
votes
1
answer
68
views
Decorator which changes ints to strings with correct type hints
I have written a decorator which changes the types of some arguments passed to a decorated function.
For example, any argument which was int should become str:
from typing import Callable
def ...
2
votes
1
answer
134
views
How to validate a TextIO argument?
I am just coming to terms with Python type hinting and I am confused how to implement argument validation for the following function signature:
def read_file(file: Union[str, PathLike, TextIO]) -> ...
1
vote
2
answers
54
views
Pydantic optinal throws `Field required` in nested json list
I have a nested json that I validate with pydantic:
app_dict={'apps': [{'app_id': 'a_1',
'group_id': '123',
'report_id': '456',
'principal_id': 'p_1'},
{'app_id': 'a_2',
'group_id': '789'...
0
votes
2
answers
43
views
Specify pydantic model fields from a data source
I have a need for a pydantic model that would dynamically create model fields from another data source. I'd like to do something like this:
import pydantic
import my_data
_data = my_data.load() # ...
0
votes
1
answer
40
views
Pylance not allowing structural subtyping with built-in types
I'm reading the document about protocols and stuck with a Pylance error message.
https://peps.python.org/pep-0544/#subtyping-relationships-with-other-types
Simplifying the code in this section, I ...
0
votes
1
answer
45
views
Python: typing, how to use an inner class from another inner class?
Is it possible to specify a parameter of an inner class function as being types as another inner class?
class MyClass():
class InnerClass1():
pass
class InnerClass2():
...
0
votes
1
answer
39
views
How to type annotate different return type depending on if a parameter is given like in case of next() function?
next() function has a special property, that next(iterable) returns the element or raises an exception, but next(iterable, None) returns an element or None.
How to type annotate it? Consider the ...
0
votes
0
answers
864
views
I cannot import name 'TypeAliasType' from 'typing_extensions'
I am new to Python and found the following error like that. I would really appreciate your comments. Thanks
I try to import Gradio library as gr
I've tried several existing suggestions, but the ...
0
votes
1
answer
58
views
import from typing within TYPE_CHECKING block?
Does it make sense to import from typing inside a TYPE_CHECKING block?
Is this good/bad or does it even matter?
from __future__ import annotations
from typing import TYPE_CHECKING, Protocol, ...
1
vote
1
answer
64
views
Add class attribute from generic annotation
I need to add attributes from a function but can't find a way for type hinting to support it.
The problem arises when trying to represent the return type using Protocol Union.
from typing import Any, ...
0
votes
1
answer
46
views
How to get rid of 'incompatible type "Callable[[NamedArg(int, 'val')], ..'?
I'm trying to forward and/or store Callables while providing as much type hinting as possible. Currently I'm struggling with a mypy error that seems simple, but I somehow cannot solve it. Imagine this ...
1
vote
1
answer
47
views
Why does mypy consider `Mapping` with more restrictions on keys/values not compatible with the one with fewer restrictions
The code below results in a mypy error
from collections.abc import Mapping
def f(a: Mapping[str | bytes, str | bytes | int | float]):
print(a)
x: Mapping[str, int] = {'a': 1}
f(x)
file.py:8: ...
3
votes
2
answers
137
views
abstractmethod returns a type of self
I'm having some problems with mypy.
I have an abstract class and a class that inherits from it:
from __future__ import annotations
from abc import abstractmethod, ABC
from typing import Union
class ...
0
votes
1
answer
116
views
Does collections.abc.Collection have a uniqueness property, like Set?
From https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes, it's clear to me that a collections.abc.Set is a collections.abc.Collection. And a useful property of Set ...
0
votes
0
answers
79
views
In Python is it possible to extract and re-use the types of variadic collections?
Is it possible to modify deco_with_params in the following snippet to accept an arbitrary number of sequences of generic types while keeping it fully type hinted?
from collections.abc import Mapping, ...
3
votes
3
answers
128
views
Pylance not working autocomplete for dynamically instantiated classes
from typing import Literal, overload, TypeVar, Generic, Type
import enum
import abc
import typing
class Version(enum.Enum):
Version1 = 1
Version2 = 2
Version3 = 3
import abc
from typing ...
0
votes
2
answers
92
views
How to type annotate optionally parametrized decorator, which use third party decorator inside
Faced with problem, when using mypy on my project. At first I use a backoff package to do some retries on some functions/methods. Then I realised, that most of options are just repeated, so I created ...
1
vote
1
answer
124
views
How to hint type a Callable without knowing all the necessary args and kwargs?
I would like to code a wrapper that takes in arguments a function, its args and kwargs and execute them but with some kwargs precisely known while others are unknown.
Exemple:
def wrapper(...
1
vote
2
answers
90
views
Is it possible to call Pyright from code (as an API)?
It seems that Pyright (the Python type checker made by Microsoft) can only be used as a command line tool or from VS Code. But is it possible to call pyright from code (as an API)?
For example, mypy ...
5
votes
0
answers
146
views
Using a pipe symbol in typing.Literal string
I have a function that accepts certain literals for a specific argument:
from typing import Literal
def fn(x: Literal["foo", "bar", "foo|bar"]) -> None:
...
0
votes
1
answer
46
views
Specify object implements protocol and inherits from class
Suppose I have a protocol
from abc import abstractmethod
from typing import Protocol
class Supports_connect(Protocol):
address: int
@abstractmethod
def connect(self) -> None:
....
1
vote
1
answer
273
views
How to type a Python function the same way as another function?
For writing a wrapper around an existing function, I want to that wrapper to have the same, or very similar, type.
For example:
import os
def my_open(*args, **kwargs):
return os.open(*args, **...
0
votes
1
answer
74
views
Correctly type hint different callback functions for the class
I'm trying to implement a class that would be able to use two types of callbacks:
callback with integer parameter named exactly as I want it to be named (to force API users to use certain parameter ...
0
votes
1
answer
75
views
Python one class produces two types
I have a src directory containing a helpers directory. Inside of the modules inside of the helpers directory,
I use
import os
import sys
sys.path.append(os.path.dirname(__file__))
to make relative ...
0
votes
0
answers
56
views
Pylance does not see stub files
I have the following structure:
mypackage/
├─ subpackage/
│ ├─ __init__.py
│ ├─ module.py
│ ├─ module.pyi
├─ __init__.py
File mudule.pyi contains:
class Apple:
tree: Tree
class Tree:
...
0
votes
0
answers
174
views
MyPy complains about isinstance(obj, Callable) being incompatible with _ClassInfo
I've got a couple of ifs that all use isinstance. One of them is checking the obj against Collable with isinstance(obj, Callable) as suggested in this answer. But when I run mypy on that code it ...
1
vote
1
answer
31
views
match-case: Bind keyword attribute to variable
When matching against a class-pattern with keyword attributes, is it possible to bind the attribute to a variable directly?
For positional arguments, it is possible via walrus operator: https://peps....
0
votes
0
answers
32
views
Override a class attribute of the type of a generic type via a mixin so mypy won’t say it’s incompatible
I have a generic base class A that has an attribute containing the generic type TK.
import typing
class K1:
pass
TK = typing.TypeVar("TK", bound=K1)
class A(typing.Generic[TK]):
k:...
3
votes
1
answer
99
views
Alias for an typable Union [duplicate]
I am looking for a way to create a type alias for a Union that is typeable.
In my opinion, there is no suitable default type in the typing module.
Typing.Iterable is an iterable, which could be a ...