Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1 | :mod:`typing` --- Support for type hints |
| 2 | ======================================== |
| 3 | |
| 4 | .. module:: typing |
| 5 | :synopsis: Support for type hints (see PEP 484). |
| 6 | |
| 7 | **Source code:** :source:`Lib/typing.py` |
| 8 | |
| 9 | -------------- |
| 10 | |
| 11 | This module supports type hints as specified by :pep:`484`. The most |
| 12 | fundamental support consists of the type :class:`Any`, :class:`Union`, |
| 13 | :class:`Tuple`, :class:`Callable`, :class:`TypeVar`, and |
| 14 | :class:`Generic`. For full specification please see :pep:`484`. For |
| 15 | a simplified introduction to type hints see :pep:`483`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 16 | |
| 17 | |
| 18 | The function below takes and returns a string and is annotated as follows:: |
| 19 | |
| 20 | def greeting(name: str) -> str: |
| 21 | return 'Hello ' + name |
| 22 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 23 | In the function ``greeting``, the argument ``name`` is expected to by of type |
| 24 | :class:`str` and the return type :class:`str`. Subtypes are accepted as |
| 25 | arguments. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 26 | |
| 27 | Type aliases |
| 28 | ------------ |
| 29 | |
| 30 | A type alias is defined by assigning the type to the alias:: |
| 31 | |
| 32 | Vector = List[float] |
| 33 | |
| 34 | Callable |
| 35 | -------- |
| 36 | |
| 37 | Frameworks expecting callback functions of specific signatures might be |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 38 | type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 39 | |
| 40 | For example:: |
| 41 | |
| 42 | from typing import Callable |
| 43 | |
| 44 | def feeder(get_next_item: Callable[[], str]) -> None: |
| 45 | # Body |
| 46 | |
| 47 | def async_query(on_success: Callable[[int], None], |
| 48 | on_error: Callable[[int, Exception], None]) -> None: |
| 49 | # Body |
| 50 | |
Guido van Rossum | 9db397c | 2015-08-05 12:26:07 +0200 | [diff] [blame] | 51 | It is possible to declare the return type of a callable without specifying |
| 52 | the call signature by substituting a literal ellipsis |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 53 | for the list of arguments in the type hint: ``Callable[..., ReturnType]``. |
| 54 | ``None`` as a type hint is a special case and is replaced by ``type(None)``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 55 | |
| 56 | Generics |
| 57 | -------- |
| 58 | |
| 59 | Since type information about objects kept in containers cannot be statically |
| 60 | inferred in a generic way, abstract base classes have been extended to support |
| 61 | subscription to denote expected types for container elements. |
| 62 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 63 | :: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 64 | |
| 65 | from typing import Mapping, Sequence |
| 66 | |
| 67 | def notify_by_email(employees: Sequence[Employee], |
| 68 | overrides: Mapping[str, str]) -> None: ... |
| 69 | |
| 70 | Generics can be parametrized by using a new factory available in typing |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 71 | called :class:`TypeVar`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 72 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 73 | :: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 74 | |
| 75 | from typing import Sequence, TypeVar |
| 76 | |
| 77 | T = TypeVar('T') # Declare type variable |
| 78 | |
| 79 | def first(l: Sequence[T]) -> T: # Generic function |
| 80 | return l[0] |
| 81 | |
| 82 | |
| 83 | User-defined generic types |
| 84 | -------------------------- |
| 85 | |
| 86 | A user-defined class can be defined as a generic class. |
| 87 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 88 | :: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 89 | |
| 90 | from typing import TypeVar, Generic |
| 91 | from logging import Logger |
| 92 | |
| 93 | T = TypeVar('T') |
| 94 | |
| 95 | class LoggedVar(Generic[T]): |
| 96 | def __init__(self, value: T, name: str, logger: Logger) -> None: |
| 97 | self.name = name |
| 98 | self.logger = logger |
| 99 | self.value = value |
| 100 | |
| 101 | def set(self, new: T) -> None: |
| 102 | self.log('Set ' + repr(self.value)) |
| 103 | self.value = new |
| 104 | |
| 105 | def get(self) -> T: |
| 106 | self.log('Get ' + repr(self.value)) |
| 107 | return self.value |
| 108 | |
| 109 | def log(self, message: str) -> None: |
| 110 | self.logger.info('{}: {}'.format(self.name, message)) |
| 111 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 112 | ``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a |
| 113 | single type parameter ``T`` . This also makes ``T`` valid as a type within the |
| 114 | class body. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 115 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 116 | The :class:`Generic` base class uses a metaclass that defines |
| 117 | :meth:`__getitem__` so that ``LoggedVar[t]`` is valid as a type:: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 118 | |
| 119 | from typing import Iterable |
| 120 | |
| 121 | def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: |
| 122 | for var in vars: |
| 123 | var.set(0) |
| 124 | |
| 125 | A generic type can have any number of type variables, and type variables may |
| 126 | be constrained:: |
| 127 | |
| 128 | from typing import TypeVar, Generic |
| 129 | ... |
| 130 | |
| 131 | T = TypeVar('T') |
| 132 | S = TypeVar('S', int, str) |
| 133 | |
| 134 | class StrangePair(Generic[T, S]): |
| 135 | ... |
| 136 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 137 | Each type variable argument to :class:`Generic` must be distinct. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 138 | This is thus invalid:: |
| 139 | |
| 140 | from typing import TypeVar, Generic |
| 141 | ... |
| 142 | |
| 143 | T = TypeVar('T') |
| 144 | |
| 145 | class Pair(Generic[T, T]): # INVALID |
| 146 | ... |
| 147 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 148 | You can use multiple inheritance with :class:`Generic`:: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 149 | |
| 150 | from typing import TypeVar, Generic, Sized |
| 151 | |
| 152 | T = TypeVar('T') |
| 153 | |
| 154 | class LinkedList(Sized, Generic[T]): |
| 155 | ... |
| 156 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 157 | When inheriting from generic classes, some type variables could fixed:: |
| 158 | |
| 159 | from typing import TypeVar, Mapping |
| 160 | |
| 161 | T = TypeVar('T') |
| 162 | |
| 163 | class MyDict(Mapping[str, T]): |
| 164 | ... |
| 165 | |
| 166 | In this case ``MyDict`` has a single parameter, ``T``. |
| 167 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 168 | Subclassing a generic class without specifying type parameters assumes |
| 169 | :class:`Any` for each position. In the following example, ``MyIterable`` is |
| 170 | not generic but implicitly inherits from ``Iterable[Any]``:: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 171 | |
| 172 | from typing import Iterable |
| 173 | |
| 174 | class MyIterable(Iterable): # Same as Iterable[Any] |
| 175 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 176 | The metaclass used by :class:`Generic` is a subclass of :class:`abc.ABCMeta`. |
| 177 | A generic class can be an ABC by including abstract methods or properties, |
| 178 | and generic classes can also have ABCs as base classes without a metaclass |
| 179 | conflict. Generic metaclasses are not supported. |
| 180 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 181 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 182 | The :class:`Any` type |
| 183 | --------------------- |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 184 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 185 | A special kind of type is :class:`Any`. Every type is a subtype of |
| 186 | :class:`Any`. This is also true for the builtin type object. However, to the |
| 187 | static type checker these are completely different. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 188 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 189 | When the type of a value is :class:`object`, the type checker will reject |
| 190 | almost all operations on it, and assigning it to a variable (or using it as a |
| 191 | return value) of a more specialized type is a type error. On the other hand, |
| 192 | when a value has type :class:`Any`, the type checker will allow all operations |
| 193 | on it, and a value of type :class:`Any` can be assigned to a variable (or used |
| 194 | as a return value) of a more constrained type. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 195 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 196 | |
| 197 | Classes, functions, and decorators |
| 198 | ---------------------------------- |
| 199 | |
| 200 | The module defines the following classes, functions and decorators: |
| 201 | |
| 202 | .. class:: Any |
| 203 | |
| 204 | Special type indicating an unconstrained type. |
| 205 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 206 | * Any object is an instance of :class:`Any`. |
| 207 | * Any class is a subclass of :class:`Any`. |
| 208 | * As a special case, :class:`Any` and :class:`object` are subclasses of |
| 209 | each other. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 210 | |
| 211 | .. class:: TypeVar |
| 212 | |
| 213 | Type variable. |
| 214 | |
| 215 | Usage:: |
| 216 | |
| 217 | T = TypeVar('T') # Can be anything |
| 218 | A = TypeVar('A', str, bytes) # Must be str or bytes |
| 219 | |
| 220 | Type variables exist primarily for the benefit of static type |
| 221 | checkers. They serve as the parameters for generic types as well |
| 222 | as for generic function definitions. See class Generic for more |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 223 | information on generic types. Generic functions work as follows:: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 224 | |
| 225 | def repeat(x: T, n: int) -> Sequence[T]: |
| 226 | """Return a list containing n references to x.""" |
| 227 | return [x]*n |
| 228 | |
| 229 | def longest(x: A, y: A) -> A: |
| 230 | """Return the longest of two strings.""" |
| 231 | return x if len(x) >= len(y) else y |
| 232 | |
| 233 | The latter example's signature is essentially the overloading |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 234 | of ``(str, str) -> str`` and ``(bytes, bytes) -> bytes``. Also note |
| 235 | that if the arguments are instances of some subclass of :class:`str`, |
| 236 | the return type is still plain :class:`str`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 237 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 238 | At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. In general, |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 239 | :func:`isinstance` and :func:`issubclass` should not be used with types. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 240 | |
| 241 | Type variables may be marked covariant or contravariant by passing |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 242 | ``covariant=True`` or ``contravariant=True``. See :pep:`484` for more |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 243 | details. By default type variables are invariant. Alternatively, |
| 244 | a type variable may specify an upper bound using ``bound=<type>``. |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 245 | This means that an actual type substituted (explicitly or implicitly) |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 246 | for the type variable must be a subclass of the boundary type, |
| 247 | see :pep:`484`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 248 | |
| 249 | .. class:: Union |
| 250 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 251 | Union type; ``Union[X, Y]`` means either X or Y. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 252 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 253 | To define a union, use e.g. ``Union[int, str]``. Details: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 254 | |
| 255 | * The arguments must be types and there must be at least one. |
| 256 | |
| 257 | * Unions of unions are flattened, e.g.:: |
| 258 | |
| 259 | Union[Union[int, str], float] == Union[int, str, float] |
| 260 | |
| 261 | * Unions of a single argument vanish, e.g.:: |
| 262 | |
| 263 | Union[int] == int # The constructor actually returns int |
| 264 | |
| 265 | * Redundant arguments are skipped, e.g.:: |
| 266 | |
| 267 | Union[int, str, int] == Union[int, str] |
| 268 | |
| 269 | * When comparing unions, the argument order is ignored, e.g.:: |
| 270 | |
| 271 | Union[int, str] == Union[str, int] |
| 272 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 273 | * If :class:`Any` is present it is the sole survivor, e.g.:: |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 274 | |
| 275 | Union[int, Any] == Any |
| 276 | |
| 277 | * You cannot subclass or instantiate a union. |
| 278 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 279 | * You cannot write ``Union[X][Y]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 280 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 281 | * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 282 | |
| 283 | .. class:: Optional |
| 284 | |
| 285 | Optional type. |
| 286 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 287 | ``Optional[X]`` is equivalent to ``Union[X, type(None)]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 288 | |
| 289 | .. class:: Tuple |
| 290 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 291 | Tuple type; ``Tuple[X, Y]`` is the is the type of a tuple of two items |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 292 | with the first item of type X and the second of type Y. |
| 293 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 294 | Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding |
| 295 | to type variables T1 and T2. ``Tuple[int, float, str]`` is a tuple |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 296 | of an int, a float and a string. |
| 297 | |
Guido van Rossum | 9db397c | 2015-08-05 12:26:07 +0200 | [diff] [blame] | 298 | To specify a variable-length tuple of homogeneous type, |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 299 | use literal ellipsis, e.g. ``Tuple[int, ...]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 300 | |
| 301 | .. class:: Callable |
| 302 | |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 303 | Callable type; ``Callable[[int], str]`` is a function of (int) -> str. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 304 | |
| 305 | The subscription syntax must always be used with exactly two |
| 306 | values: the argument list and the return type. The argument list |
| 307 | must be a list of types; the return type must be a single type. |
| 308 | |
| 309 | There is no syntax to indicate optional or keyword arguments, |
Guido van Rossum | 9db397c | 2015-08-05 12:26:07 +0200 | [diff] [blame] | 310 | such function types are rarely used as callback types. |
Zachary Ware | ce50802 | 2015-08-29 22:39:47 -0500 | [diff] [blame] | 311 | ``Callable[..., ReturnType]`` could be used to type hint a callable |
| 312 | taking any number of arguments and returning ``ReturnType``. |
| 313 | A plain :class:`Callable` is equivalent to ``Callable[..., Any]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 314 | |
| 315 | .. class:: Generic |
| 316 | |
| 317 | Abstract base class for generic types. |
| 318 | |
| 319 | A generic type is typically declared by inheriting from an |
| 320 | instantiation of this class with one or more type variables. |
| 321 | For example, a generic mapping type might be defined as:: |
| 322 | |
| 323 | class Mapping(Generic[KT, VT]): |
| 324 | def __getitem__(self, key: KT) -> VT: |
| 325 | ... |
| 326 | # Etc. |
| 327 | |
| 328 | This class can then be used as follows:: |
| 329 | |
| 330 | X = TypeVar('X') |
| 331 | Y = TypeVar('Y') |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 332 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 333 | def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: |
| 334 | try: |
| 335 | return mapping[key] |
| 336 | except KeyError: |
Guido van Rossum | 9db397c | 2015-08-05 12:26:07 +0200 | [diff] [blame] | 337 | return default |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 338 | |
| 339 | .. class:: Iterable(Generic[T_co]) |
| 340 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 341 | A generic version of the :class:`collections.abc.Iterable`. |
| 342 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 343 | .. class:: Iterator(Iterable[T_co]) |
| 344 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 345 | A generic version of the :class:`collections.abc.Iterator`. |
| 346 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 347 | .. class:: SupportsInt |
| 348 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 349 | An ABC with one abstract method ``__int__``. |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 350 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 351 | .. class:: SupportsFloat |
| 352 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 353 | An ABC with one abstract method ``__float__``. |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 354 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 355 | .. class:: SupportsAbs |
| 356 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 357 | An ABC with one abstract method ``__abs__`` that is covariant |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 358 | in its return type. |
| 359 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 360 | .. class:: SupportsRound |
| 361 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 362 | An ABC with one abstract method ``__round__`` |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 363 | that is covariant in its return type. |
| 364 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 365 | .. class:: Reversible |
| 366 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 367 | An ABC with one abstract method ``__reversed__`` returning |
| 368 | an ``Iterator[T_co]``. |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 369 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 370 | .. class:: Container(Generic[T_co]) |
| 371 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 372 | A generic version of :class:`collections.abc.Container`. |
| 373 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 374 | .. class:: AbstractSet(Sized, Iterable[T_co], Container[T_co]) |
| 375 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 376 | A generic version of :class:`collections.abc.Set`. |
| 377 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 378 | .. class:: MutableSet(AbstractSet[T]) |
| 379 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 380 | A generic version of :class:`collections.abc.MutableSet`. |
| 381 | |
| 382 | .. class:: Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co]) |
| 383 | |
| 384 | A generic version of :class:`collections.abc.Mapping`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 385 | |
| 386 | .. class:: MutableMapping(Mapping[KT, VT]) |
| 387 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 388 | A generic version of :class:`collections.abc.MutableMapping`. |
| 389 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 390 | .. class:: Sequence(Sized, Iterable[T_co], Container[T_co]) |
| 391 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 392 | A generic version of :class:`collections.abc.Sequence`. |
| 393 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 394 | .. class:: MutableSequence(Sequence[T]) |
| 395 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 396 | A generic version of :class:`collections.abc.MutableSequence`. |
| 397 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 398 | .. class:: ByteString(Sequence[int]) |
| 399 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 400 | A generic version of :class:`collections.abc.ByteString`. |
| 401 | |
| 402 | This type represents the types :class:`bytes`, :class:`bytearray`, |
| 403 | and :class:`memoryview`. |
| 404 | |
| 405 | As a shorthand for this type, :class:`bytes` can be used to |
| 406 | annotate arguments of any of the types mentioned above. |
| 407 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 408 | .. class:: List(list, MutableSequence[T]) |
| 409 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 410 | Generic version of :class:`list`. |
| 411 | Useful for annotating return types. To annotate arguments it is preferred |
| 412 | to use abstract collection types such as :class:`Mapping`, :class:`Sequence`, |
| 413 | or :class:`AbstractSet`. |
| 414 | |
| 415 | This type may be used as follows:: |
| 416 | |
| 417 | T = TypeVar('T', int, float) |
| 418 | |
| 419 | def vec2(x: T, y: T) -> List[T]: |
| 420 | return [x, y] |
| 421 | |
| 422 | def slice__to_4(vector: Sequence[T]) -> List[T]: |
| 423 | return vector[0:4] |
| 424 | |
| 425 | .. class:: AbstractSet(set, MutableSet[T]) |
| 426 | |
| 427 | A generic version of :class:`collections.abc.Set`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 428 | |
| 429 | .. class:: MappingView(Sized, Iterable[T_co]) |
| 430 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 431 | A generic version of :class:`collections.abc.MappingView`. |
| 432 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 433 | .. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co]) |
| 434 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 435 | A generic version of :class:`collections.abc.KeysView`. |
| 436 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 437 | .. class:: ItemsView(MappingView, Generic[KT_co, VT_co]) |
| 438 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 439 | A generic version of :class:`collections.abc.ItemsView`. |
| 440 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 441 | .. class:: ValuesView(MappingView[VT_co]) |
| 442 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 443 | A generic version of :class:`collections.abc.ValuesView`. |
| 444 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 445 | .. class:: Dict(dict, MutableMapping[KT, VT]) |
| 446 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 447 | A generic version of :class:`dict`. |
| 448 | The usage of this type is as follows:: |
| 449 | |
| 450 | def get_position_in_index(word_list: Dict[str, int], word: str) -> int: |
| 451 | return word_list[word] |
| 452 | |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 453 | .. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) |
| 454 | |
| 455 | .. class:: io |
| 456 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 457 | Wrapper namespace for I/O stream types. |
| 458 | |
| 459 | This defines the generic type ``IO[AnyStr]`` and aliases ``TextIO`` |
| 460 | and ``BinaryIO`` for respectively ``IO[str]`` and ``IO[bytes]``. |
| 461 | These representing the types of I/O streams such as returned by |
| 462 | :func:`open`. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 463 | |
| 464 | .. class:: re |
| 465 | |
Guido van Rossum | 2a19d95 | 2015-09-10 10:52:11 -0700 | [diff] [blame] | 466 | Wrapper namespace for regular expression matching types. |
| 467 | |
| 468 | This defines the type aliases ``Pattern`` and ``Match`` which |
| 469 | correspond to the return types from :func:`re.compile` and |
| 470 | :func:`re.match`. These types (and the corresponding functions) |
| 471 | are generic in ``AnyStr`` and can be made specific by writing |
| 472 | ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or |
| 473 | ``Match[bytes]``. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 474 | |
| 475 | .. function:: NamedTuple(typename, fields) |
| 476 | |
| 477 | Typed version of namedtuple. |
| 478 | |
| 479 | Usage:: |
| 480 | |
| 481 | Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)]) |
| 482 | |
| 483 | This is equivalent to:: |
| 484 | |
| 485 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 486 | |
| 487 | The resulting class has one extra attribute: _field_types, |
| 488 | giving a dict mapping field names to types. (The field names |
| 489 | are in the _fields attribute, which is part of the namedtuple |
| 490 | API.) |
| 491 | |
| 492 | .. function:: cast(typ, val) |
| 493 | |
| 494 | Cast a value to a type. |
| 495 | |
| 496 | This returns the value unchanged. To the type checker this |
| 497 | signals that the return value has the designated type, but at |
| 498 | runtime we intentionally don't check anything (we want this |
| 499 | to be as fast as possible). |
| 500 | |
| 501 | .. function:: get_type_hints(obj) |
| 502 | |
| 503 | Return type hints for a function or method object. |
| 504 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 505 | This is often the same as ``obj.__annotations__``, but it handles |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 506 | forward references encoded as string literals, and if necessary |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 507 | adds ``Optional[t]`` if a default value equal to None is set. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 508 | |
| 509 | .. decorator:: no_type_check(arg) |
| 510 | |
| 511 | Decorator to indicate that annotations are not type hints. |
| 512 | |
| 513 | The argument must be a class or function; if it is a class, it |
| 514 | applies recursively to all methods defined in that class (but not |
| 515 | to methods defined in its superclasses or subclasses). |
| 516 | |
| 517 | This mutates the function(s) in place. |
| 518 | |
| 519 | .. decorator:: no_type_check_decorator(decorator) |
| 520 | |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 521 | Decorator to give another decorator the :func:`no_type_check` effect. |
Guido van Rossum | eb184e0 | 2015-08-03 22:35:46 +0200 | [diff] [blame] | 522 | |
| 523 | This wraps the decorator with something that wraps the decorated |
Berker Peksag | 573e2cd | 2015-09-10 21:55:50 +0300 | [diff] [blame] | 524 | function in :func:`no_type_check`. |