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
235
votes
3 answers

Type hints in namedtuple

Consider following piece of code: from collections import namedtuple point = namedtuple("Point", ("x:int", "y:int")) The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints. Do…
213
votes
3 answers

Subclass in type hinting

I want to allow type hinting using Python 3 to accept sub classes of a certain class. E.g.: class A: pass class B(A): pass class C(A): pass def process_any_subclass_type_of_A(cls: A): if cls == B: # do something elif…
user1211030
  • 2,680
  • 2
  • 19
  • 22
205
votes
2 answers

Type hints with user defined classes

Couldn't seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass(). And then let's say in some function, call it FuncA(arg), I have one argument named…
hhprogram
  • 2,809
  • 3
  • 13
  • 25
192
votes
5 answers

Type hinting / annotation (PEP 484) for numpy.ndarray

Has anyone implemented type hinting for the specific numpy.ndarray class? Right now, I'm using typing.Any, but it would be nice to have something more specific. For instance if the NumPy people added a type alias for their array_like object class.…
Inon
  • 2,106
  • 3
  • 12
  • 17
175
votes
5 answers

How can I tell PyCharm what type a parameter is expected to be?

When it comes to constructors, and assignments, and method calls, the PyCharm IDE is pretty good at analyzing my source code and figuring out what type each variable should be. I like it when it's right, because it gives me good code-completion and…
Joe White
  • 94,807
  • 60
  • 220
  • 330
163
votes
3 answers

How to type hint a generator in Python 3?

According to PEP-484, we should be able to type hinting a generator function as follows: from typing import Generator def generate() -> Generator[int, None, None]: for i in range(10): yield i for i in generate(): print(i) However,…
Jinho Choi
  • 1,841
  • 2
  • 10
  • 12
130
votes
3 answers

How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)

I have a function that takes a tuple of different lengths as an argument: from typing import Tuple def process_tuple(t: Tuple[str]): # Do nasty tuple stuff process_tuple(("a",)) process_tuple(("a", "b")) process_tuple(("a", "b", "c")) When…
Montreal
  • 2,143
  • 5
  • 18
  • 28
127
votes
2 answers

What are variable annotations?

Python 3.6 is about to be released. PEP 494 -- Python 3.6 Release Schedule mentions the end of December, so I went through What's New in Python 3.6 to see they mention the variable annotations: PEP 484 introduced standard for type annotations of…
fedorqui
  • 275,237
  • 103
  • 548
  • 598
124
votes
5 answers

Type annotations for Enum attribute

I have this piece of code: import enum class Color(enum.Enum): RED = '1' BLUE = '2' GREEN = '3' def get_color_return_something(some_color): pass How do I properly add type annotations to the some_color variable in this function,…
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
122
votes
2 answers

Type hints when unpacking a tuple?

Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError: from typing import Tuple t: Tuple[int, int] = (1, 2) a: int, b: int = t # ^ SyntaxError: invalid syntax
Cai
  • 1,726
  • 2
  • 15
  • 24
121
votes
1 answer

What is the difference between TypeVar and NewType?

TypeVar and NewType seem related but I'm not sure when I'm supposed to use each or what the difference is at runtime and statically.
Hatshepsut
  • 5,962
  • 8
  • 44
  • 80
113
votes
4 answers

NameError: name 'List' is not defined

I'm really unsure why this isn't working. Here is the important part of the code (it's from a leetcode challenge). The first line throws the NameError. def totalFruit(self, tree: List[int]) -> int: pass If I try importing List first I get an…
Ariel Frischer
  • 1,406
  • 2
  • 12
  • 20
109
votes
4 answers

mypy, type hint: Union[float, int] -> is there a Number type?

mypy is really handy and catches a lot of bugs, but when I write "scientific" applications, I often end up doing: def my_func(number: Union[float, int]): # Do something number is either a float or int, depending on the user's input. Is there an…
JPFrancoia
  • 4,866
  • 10
  • 43
  • 73
107
votes
1 answer

How to annotate a type that's a class object (instead of a class instance)?

What is the proper way to annotate a function argument that expects a class object instead of an instance of that class? In the example below, some_class argument is expected to be a type instance (which is a class), but the problem here is that…
Gomes J. A.
  • 1,235
  • 2
  • 9
  • 9
107
votes
2 answers

typing.Any vs object?

Is there any difference between using typing.Any as opposed to object in typing? For example: def get_item(L: list, i: int) -> typing.Any: return L[i] Compared to: def get_item(L: list, i: int) -> object: return L[i]
Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119