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
104
votes
4 answers

Python type hinting with exceptions

I have a function that looks like this: def check_for_errors(result): if 'success' in result: return True if 'error' in result: raise TypeError return False In successful run of this function, I should get a bool, but…
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
93
votes
3 answers

Type annotation for classmethod returning instance

How should I annotate a @classmethod that returns an instance of cls? Here's a bad example: class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> ???: …
taway
  • 1,099
  • 1
  • 7
  • 9
90
votes
2 answers

Type hints: solve circular dependency

The following produces NameError: name 'Client' is not defined. How can I solve it? class Server: def register_client(self, client: Client) pass class Client: def __init__(self, server: Server): …
Tamriel
  • 1,337
  • 1
  • 9
  • 9
85
votes
4 answers

Validating detailed types in python dataclasses

Python 3.7 was released a while ago, and I wanted to test some of the fancy new dataclass+typing features. Getting hints to work right is easy enough, with both native types and those from the typing module: >>> import dataclasses >>> import typing…
Arne
  • 17,706
  • 5
  • 83
  • 99
84
votes
2 answers

Python 3 dictionary with known keys typing

I'm using Python 3 typing feature for better autocomplete. Many times I have functions that return key/value (dictionary) with specific keys. super simple example: def get_info(name): name_first_letter = name[0] return {'my_name': name,…
Idok
  • 3,642
  • 4
  • 21
  • 18
83
votes
4 answers

Specify length of Sequence or List with Python typing module

I'm giving the Python typing module a shot. I know that it's valid to specify the length of a List like the following*: List[float, float, float] # List of 3 floats <-- NOTE: this is not valid Python Is there any shorthand for longer lists? What…
John Brodie
  • 971
  • 1
  • 6
  • 5
78
votes
4 answers

How do you alias a type in Python?

In some (mostly functional) languages you can do something like this: type row = list(datum) or type row = [datum] So that we can build things like this: type row = [datum] type table = [row] type database = [table] Is there a way to do this in…
Lara
  • 2,594
  • 4
  • 24
  • 36
74
votes
1 answer

How do I specify multiple types for a parameter using type-hints?

I have a Python function which accepts XML data as an str. For convenience, the function also checks for xml.etree.ElementTree.Element and will automatically convert to str if necessary. import xml.etree.ElementTree as ET def post_xml(data: str): …
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
72
votes
2 answers

python typing signature (typing.Callable) for function with kwargs

I heavily use python typing support from python 3. Recently I was trying to pass a function as an argument and I do not find any help for using kwargs in typing.Callable signature. Please check the code below and the comments. import typing # some…
Praveen Kulkarni
  • 2,816
  • 1
  • 23
  • 39
70
votes
1 answer

Python typing for module type

I am dynamically loading a Python module using importlib.import_module as follows def load_module(mod_name: str) -> ???: return importlib.import_module(mod_name) Can somebody tell me what is the correct type annotation for a module…
andrekupka
  • 819
  • 2
  • 8
  • 6
69
votes
2 answers

Name not defined in type annotation

I'm currently working on creating a python linear algebra module for fun and for practice with the language. I recently tried to add type annotations to the module, as such: class Vector: # Various irrelevant implementation details def…
MutantOctopus
  • 3,431
  • 4
  • 22
  • 31
65
votes
4 answers

Python 3 type hinting for decorator

Consider the following code: from typing import Callable, Any TFunc = Callable[..., Any] def get_authenticated_user(): return "John" def require_auth() -> Callable[TFunc, TFunc]: def decorator(func: TFunc) -> TFunc: def wrapper(*args,…
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
63
votes
4 answers

typing: Dynamically Create Literal Alias from List of Valid Values

I have a function which validates its argument to accept only values from a given list of valid options. Typing-wise, I reflect this behavior using a Literal type alias, like so: from typing import Literal VALID_ARGUMENTS = ['foo',…
Jonathan Scholbach
  • 4,925
  • 3
  • 23
  • 44
63
votes
9 answers

Python: Typehints for argparse.Namespace objects

Is there a way to have Python static analyzers (e.g. in PyCharm, other IDEs) pick up on Typehints on argparse.Namespace objects? Example: parser = argparse.ArgumentParser() parser.add_argument('--somearg') parsed =…
Billy
  • 5,179
  • 2
  • 27
  • 53
62
votes
2 answers

Difference between TypeVar('T', A, B) and TypeVar('T', bound=Union[A, B])

What's the difference between the following two TypeVars? from typing import TypeVar, Union class A: pass class B: pass T = TypeVar("T", A, B) T = TypeVar("T", bound=Union[A, B]) Here's an example of something I don't get: this passes type…
joel
  • 6,359
  • 2
  • 30
  • 55