@@ -72,6 +72,23 @@ Type aliases are also valid type hints::
72
72
def retry(url: str, retry_count: integer): ...
73
73
74
74
75
+ Callbacks
76
+ ---------
77
+
78
+ Frameworks expecting callback functions of specific signatures might be
79
+ type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. Examples::
80
+
81
+ def feeder(get_next_item: Callable[[], Item]): ...
82
+
83
+ def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]): ...
84
+
85
+ def partial(func: Callable[AnyArgs, Any], *args): ...
86
+
87
+ Since using callbacks with keyword arguments is not perceived as
88
+ a common use case, there is currently no support for specifying keyword
89
+ arguments with ``Callable``.
90
+
91
+
75
92
Generics
76
93
--------
77
94
@@ -85,7 +102,7 @@ elements. Example::
85
102
def notify_by_email(employees: Set[Employee], overrides: Mapping[str, str]): ...
86
103
87
104
Generics can be parametrized by using a new factory available in
88
- ``collections.abc `` called ``TypeVar``. Example::
105
+ ``typing `` called ``TypeVar``. Example::
89
106
90
107
T = TypeVar('T') # Declare type variable
91
108
@@ -157,8 +174,8 @@ for example, the above is equivalent to::
157
174
158
175
def handle_employee(e: Optional[Employee]): ...
159
176
160
- An optional type is also automatically assumed when the default value
161
- is ``None``, for example:
177
+ An optional type is also automatically assumed when the default value is
178
+ ``None``, for example: :
162
179
163
180
def handle_employee(e: Employee = None): ...
164
181
@@ -173,6 +190,41 @@ A special kind of union type is ``Any``, a class that responds
173
190
explicitly state that there are no constraints on the type of a
174
191
specific argument or return value.
175
192
193
+ Platform-specific type checking
194
+ -------------------------------
195
+
196
+ In some cases the typing information will depend on the platform that
197
+ the program is being executed on. To enable specifying those
198
+ differences, simple conditionals can be used::
199
+
200
+ if PY2:
201
+ text = unicode
202
+ else:
203
+ text = str
204
+
205
+ def f() -> text: ...
206
+
207
+ if WINDOWS:
208
+ loop = ProactorEventLoop
209
+ else:
210
+ loop = UnixSelectorEventLoop
211
+
212
+ Arbitrary literals defined in the form of ``NAME = True`` will also be
213
+ accepted by the type checker to differentiate type resolution::
214
+
215
+ DEBUG = False
216
+ ...
217
+ if DEBUG:
218
+ class Tracer:
219
+ <verbose implementation>
220
+ else:
221
+ class Tracer:
222
+ <dummy implementation>
223
+
224
+ For the purposes of type hinting, the type checker assumes ``__debug__``
225
+ is set to ``True``, in other words the ``-O`` command-line option is not
226
+ used while type checking.
227
+
176
228
177
229
Compatibility with other uses of function annotations
178
230
-----------------------------------------------------
@@ -185,7 +237,14 @@ and storing annotations in the ``__annotations__`` attribute of the
185
237
function object), this does not make the program incorrect -- it just
186
238
makes it issue warnings when a static analyzer is used.
187
239
188
- .. FIXME: Define a way to shut up the static analyzer for a module, class or function.
240
+ To mark portions of the program that should not be covered by type
241
+ hinting, use the following:
242
+
243
+ * a ``@no_type_checks`` decorator on classes and functions
244
+
245
+ * a ``# type: ignore`` comment on arbitrary lines
246
+
247
+ .. FIXME: should we have a module-wide comment as well?
189
248
190
249
191
250
Type Hints on Local and Global Variables
@@ -197,6 +256,12 @@ complex cases, a comment of the following format may be used::
197
256
198
257
x = [] # type: List[Employee]
199
258
259
+ In the case where type information for a local variable is needed before
260
+ if was declared, an ``Undefined`` placeholder might be used::
261
+
262
+ x = Undefined # type: List[Employee]
263
+ y = Undefined(int)
264
+
200
265
If type hinting proves useful in general, a syntax for typing variables
201
266
may be provided in a future Python version.
202
267
@@ -210,14 +275,13 @@ documentational, in which case the recommendation is to put this
210
275
information in a docstring.
211
276
212
277
213
- The ``typing`` module
214
- =====================
215
-
216
- .. FIXME: Reconsider changing collections.abc, in favor of requiring
217
- the new types to be import from typing.py.
278
+ The ``typing`` package
279
+ ======================
218
280
219
- To enable generics on builtin types, a set of classes is introduced in
220
- a new module called ``typing``. Those classes are as follows:
281
+ To open the usage of static type checking to Python 3.5 as well as older
282
+ versions, a uniform namespace is required. For this purpose, a new
283
+ package in the standard library is introduced called ``typing``. It
284
+ holds a set of classes representing builtin types with generics, namely:
221
285
222
286
* Dict, used as ``Dict[key_type, value_type]``
223
287
@@ -233,18 +297,28 @@ a new module called ``typing``. Those classes are as follows:
233
297
case the following arguments are considered the same type as the last
234
298
defined type on the tuple.
235
299
236
- To open the usage of static type checking to Python 3 versions older
237
- than 3.5, the new and modified types found in the ``collections.abc``
238
- module are also importable from the ``typing`` module. The following
239
- new members are defined:
300
+ It also introduces factories and helper members needed to express
301
+ generics and union types:
302
+
303
+ * Any, used as ``def get(key: str) -> Any: ...``
240
304
241
- * Any
305
+ * Union, used as ``Union[Type1, Type2, Type3]``
242
306
243
- * Union
307
+ * TypeVar, used as ``X = TypeVar('X', Type1, Type2, Type3)`` or simply
308
+ ``Y = TypeVar('Y')``
244
309
245
- * TypeVar
310
+ * Undefined, used as ``local_variable = Undefined # type: List[int]`` or
311
+ ``local_variable = Undefined(List[int])`` (the latter being slower
312
+ during runtime)
313
+
314
+ * Callable, used as ``Callable[[Arg1Type, Arg2Type], ReturnType]``
315
+
316
+ * AnyArgs, used as ``Callable[AnyArgs, ReturnType]``
317
+
318
+ * AnyStr, equivalent to ``TypeVar('AnyStr', str, bytes)``
246
319
247
- All available abstract base classes are importable:
320
+ All abstract base classes available in ``collections.abc`` are
321
+ importable from the ``typing`` package, with added generics support:
248
322
249
323
* ByteString
250
324
@@ -283,19 +357,32 @@ All available abstract base classes are importable:
283
357
284
358
* Mapping
285
359
360
+ The library includes literals for platform-specific type hinting:
361
+
362
+ * PY2
363
+
364
+ * PY3, equivalent to ``not PY2``
365
+
366
+ * WINDOWS
367
+
368
+ * UNIXOID, equivalent to ``not WINDOWS``
369
+
370
+ The following types are available in the ``typing.io`` module:
371
+
286
372
* IO
287
373
288
374
* BinaryIO
289
375
290
376
* TextIO
291
377
292
- The following helper types are also provided by the ``typing`` module:
293
-
294
- * AnyStr, equivalent to ``TypeVar('AnyStr', str, bytes)``
378
+ The following types are provided by the ``typing.re`` module:
295
379
296
- * Match and Pattern, types of ``re.match()`` and ``re.compile()`` results
380
+ * Match and Pattern, types of ``re.match()`` and ``re.compile()``
381
+ results
297
382
298
- .. FIXME: Match, Pattern and the IO types don't really belong here.
383
+ As a convenience measure, types from ``typing.io`` and ``typing.re`` are
384
+ also available in ``typing`` (quoting Guido, "There's a reason those
385
+ modules have two-letter names.").
299
386
300
387
301
388
The place of the ``typing`` module in the standard library
0 commit comments