Questions tagged [python-typing]

For questions related to PEP 484 (Type Hints), PEP 526 (Syntax for Variable Annotations) and the `typing` module.

Type hints in python, as specified by PEP 484 and PEP 483, are an optional feature that allow for detailed static analysis of python source code by third-party type-checkers. Popular third-party type-checkers include MyPy, Pylance, Pyright, Pyre, and PyCharm's builtin type-checker.

Support for type hints in python is provided by the typing module. Discussions regarding proposed enhancements to the typing module and python-typing syntax take place on the typing-sig mailing list.


Relevant PEPs

Since PEP 484, a number of subsequent PEPs have modified, enhanced and extended Python's framework for type annotations, including:

  • PEP 526: "Syntax for Variable Annotations"

  • PEP 544: "Protocols: Structural subtyping (static duck typing)"

  • PEP 561: "Distributing and Packaging Type Information"

  • PEP 563: "Postponed Evaluation of Annotations"

    See also: the April 2021 statement by the Python Steering Council regarding the future of this PEP.

  • PEP 585: "Type Hinting Generics In Standard Collections"

  • PEP 586: "Literal Types"

  • PEP 589: "TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys"

  • PEP 591: "Adding a final qualifier to typing"

  • PEP 593: "Flexible function and variable annotations"

    Introducing typing.Annotated

  • PEP 604: "Allow writing union types as X | Y"

  • PEP 612: "Parameter Specification Variables"

  • PEP 613: "Explicit Type Aliases"

  • PEP 647: "User-Defined Type Guards"

1841 questions
0
votes
1 answer

Generic list in NamedTuple in python3.4

I want to define new type which holds list of generic values. For example (simplified as much as possible): from typing import NamedTuple, TypeVar, List T = TypeVar('T') MyType = NamedTuple('MyType', [('values', List[T])]) but this doesn't work and…
Jan Spurny
  • 5,219
  • 1
  • 33
  • 47
0
votes
0 answers

How do I state that I want any number of types for an instance of a generic class in Python?

Let's say I wanted to create a generic class so that it can be used similarly to the following: list[int] list[int, float] list[int, str] If I am not mistaken, the first object represents a list of integers, the second object represents a list of…
user18798042
  • 107
  • 7
0
votes
0 answers

PyQt6. Operator "-" not supported for types "QPoint" and "QPoint". Pylance(reportGeneralTypeIssues)

self.move(qt_rectangle.topLeft() - QPoint(6, 0)) Is there any way to fix this error? I think it's the wrong type annotations in the PyQt6 framework for python, cause "+", "-" operands on QPoint are supported for sure.
monotype
  • 217
  • 2
  • 10
0
votes
1 answer

mypy: How to apply *args on a Callable type?

I have a function like below, def run_the_f(f): # run f function after some validation Based on some condition, the signature of f function changes like f(1.0), f(1.0,2.0), f(1.0,2.0,3.0,..). In other words, the number of input arguments can be…
Selva
  • 951
  • 7
  • 23
0
votes
1 answer

String lower method does not retain the generic type

def cart(fruit: Literal["apple", "orange"]): print(fruit) my_fruit = "Apple" cart(my_fruit.lower()) # <======= SYNTAX ERROR Argument of type "LiteralString" cannot be assigned to parameter "fruit" of type "Literal['apple', 'orange']" in…
Ibrahim Ali
  • 2,083
  • 2
  • 15
  • 36
0
votes
1 answer

Annotate generic base class

I'm creating the base repository class and getting the following error: from typing import Any, Generic, Type, TypeVar from sqlmodel import Session, SQLModel, select from app.models.base import BaseModel from app.models.notification import…
Symonen
  • 628
  • 2
  • 7
  • 19
0
votes
0 answers

How can I manually specify a parameter's generic type with a `TypeVar` in Python?

I have some classes that use generic types by inheriting from typing.Generic. In methods of these classes, the self parameter retains the generic type of the object; for example, in iter_1() below, the type of self is inferred as…
Jackson H
  • 171
  • 10
0
votes
2 answers

Python3: pass type as function parameter

How can I pass int or str as function parameters in python? Example: def fn(type:): # do something output = fn(type=int) Example 2 from django commands: parser.add_argument( 'years', type=int, help="Determines how many…
Zkh
  • 490
  • 1
  • 4
  • 16
0
votes
1 answer

Parameterize a parameterized type in Python 3.8

I am trying to type a decorator factory, whose basic structure isn't any real surprise: def make_wrapped_awaitable_or_aiter( awaitable_or_aiter, span_wrapper, ContextManager] ) -> AwaitableOrAIterT: if isinstance(awaitable_or_aiter,…
A. Wilson
  • 8,534
  • 1
  • 26
  • 39
0
votes
1 answer

How to type annotate parameters as 'proper' class instances or 'anything but primitives'

I was wondering whether there is a type for objects that are 'proper' class instances. Something that either communicates 'object should work with setattr' or 'anything but primitives' since even primitives are instances of object and have…
aleneum
  • 2,083
  • 12
  • 29
0
votes
1 answer

Callback protocol with unbound method

from typing import Protocol class MyObj: def my_method(self, name: str): pass class Proto(Protocol): def __call__(self, obj: MyObj, name: str): pass def my_fn(obj: MyObj, name: str): pass def caller(fn: Proto): …
0
votes
1 answer

Generic *args type declared in subclass

What I want A base class has __init__ method that accepts *args Different child classes can specify different sets of *args Each child class defines a type of accepted *args. Type checker (mypy) understands this (i.e. detects cases when child class…
jbet
  • 452
  • 4
  • 12
0
votes
1 answer

How to annotate a type that is a combination of multiple duck-types?

Let's say I want to annotate the parameter to a function, and it should satisfy both typing.Sized and typing.Hashable (any other 2+ types could apply, I just picked these two for the sake of example). How would I annotate this? Given that one can…
theberzi
  • 2,142
  • 3
  • 20
  • 34
0
votes
1 answer

Python generics: user defined generic in a callable

I have the following setup: T = TypeVar("T") @dataclass class Type(Generic[T]): name: str data: T @dataclass class Aspect: name: str from: Type[str] to: Type[int] func: Callable[[Type[str]], Type[int]] This works great,…
oddbit
  • 25
  • 5
0
votes
1 answer

What does Ellipses mean when used as the return type in Python, and why use it?

I have researched the Ellipses for Python and already read many threads and blog posts online, most relevantly this stack overflow thread. Also have read the python documentation on Ellipses. What no article/documentation has covered thus far is…
stefani
  • 9
  • 1
1 2 3
99
100