You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/source/kinds_of_types.rst
+89Lines changed: 89 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -241,6 +241,95 @@ more specific type:
241
241
since the caller may have to use :py:func:`isinstance` before doing anything
242
242
interesting with the value.
243
243
244
+
.. _alternative_union_syntax:
245
+
246
+
Alternative union syntax
247
+
------------------------
248
+
249
+
`PEP 604 <https://www.python.org/dev/peps/pep-0604/>`_ introduced an alternative way
250
+
for writing union types. Starting with **Python 3.10** it is possible to write
251
+
``Union[int, str]`` as ``int | str``. Any of the following options is possible
252
+
253
+
.. code-block:: python
254
+
255
+
from typing import List
256
+
257
+
# Use as Union
258
+
t1: int|str# equivalent to Union[int, str]
259
+
260
+
# Use as Optional
261
+
t2: int|None# equivalent to Optional[int]
262
+
263
+
# Use in generics
264
+
t3: List[int|str] # equivalent to List[Union[int, str]]
265
+
266
+
# Use in type aliases
267
+
T4 =int|None
268
+
x: T4
269
+
270
+
# Quoted variable annotations
271
+
t5: "int | str"
272
+
273
+
# Quoted function annotations
274
+
deff(t6: "int | str") -> None: ...
275
+
276
+
# Type comments
277
+
t6 =42# type:int | str
278
+
279
+
It is possible to use most of these even for earlier versions. However there are some
280
+
limitations to be aware of.
281
+
282
+
.. _alternative_union_syntax_stub_files:
283
+
284
+
Stub files
285
+
""""""""""
286
+
287
+
All options are supported, regardless of the Python version the project uses.
288
+
289
+
.. _alternative_union_syntax_37:
290
+
291
+
Python 3.7 - 3.9
292
+
""""""""""""""""
293
+
294
+
It is necessary to add ``from __future__ import annotations`` to delay the evaluation
295
+
of type annotations. Not using it would result in a ``TypeError``.
296
+
This does not apply for **type comments**, **quoted function** and **quoted variable** annotations,
297
+
as those also work for earlier versions, see :ref:`below <alternative_union_syntax_older_version>`.
298
+
299
+
.. warning::
300
+
301
+
Type aliases are **NOT** supported! Those result in a ``TypeError`` regardless
302
+
if the evaluation of type annotations is delayed.
303
+
304
+
Dynamic evaluation of annotations is **NOT** possible (e.g. ``typing.get_type_hints`` and ``eval``).
305
+
See `note PEP 604 <https://www.python.org/dev/peps/pep-0604/#change-only-pep-484-type-hints-to-accept-the-syntax-type1-type2>`_. Use ``typing.Union`` instead!
0 commit comments