summaryrefslogtreecommitdiffstats
path: root/Lib/typing.py
diff options
context:
space:
mode:
authorIvan Levkivskyi <levkivskyi@gmail.com>2019-05-26 08:37:48 (GMT)
committerGitHub <noreply@github.com>2019-05-26 08:37:48 (GMT)
commitb891c465bb7d38a597c5c2ad547d7b19194f4dad (patch)
tree1b250227315edde01664d700c509baa3a9661ca9 /Lib/typing.py
parentf367242d10ef36db38133a39ab7627f63099cba4 (diff)
downloadcpython-b891c465bb7d38a597c5c2ad547d7b19194f4dad.zip
cpython-b891c465bb7d38a597c5c2ad547d7b19194f4dad.tar.gz
cpython-b891c465bb7d38a597c5c2ad547d7b19194f4dad.tar.bz2
bpo-37046: PEP 586: Add Literal to typing module (#13572)
The implementation is straightforward and essentially is just copied from `typing_extensions`.
Diffstat (limited to 'Lib/typing.py')
-rw-r--r--Lib/typing.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index 06a7eb0..1044cc4 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -37,6 +37,7 @@ __all__ = [
'ClassVar',
'Final',
'Generic',
+ 'Literal',
'Optional',
'Tuple',
'Type',
@@ -355,6 +356,10 @@ class _SpecialForm(_Final, _Immutable, _root=True):
if self._name == 'Optional':
arg = _type_check(parameters, "Optional[t] requires a single type.")
return Union[arg, type(None)]
+ if self._name == 'Literal':
+ # There is no '_type_check' call because arguments to Literal[...] are
+ # values, not types.
+ return _GenericAlias(self, parameters)
raise TypeError(f"{self} is not subscriptable")
@@ -451,6 +456,28 @@ Optional = _SpecialForm('Optional', doc=
Optional[X] is equivalent to Union[X, None].
""")
+Literal = _SpecialForm('Literal', doc=
+ """Special typing form to define literal types (a.k.a. value types).
+
+ This form can be used to indicate to type checkers that the corresponding
+ variable or function parameter has a value equivalent to the provided
+ literal (or one of several literals):
+
+ def validate_simple(data: Any) -> Literal[True]: # always returns True
+ ...
+
+ MODE = Literal['r', 'rb', 'w', 'wb']
+ def open_helper(file: str, mode: MODE) -> str:
+ ...
+
+ open_helper('/some/path', 'r') # Passes type check
+ open_helper('/other/path', 'typo') # Error in type checker
+
+ Literal[...] cannot be subclassed. At runtime, an arbitrary value
+ is allowed as type argument to Literal[...], but type checkers may
+ impose restrictions.
+ """)
+
class ForwardRef(_Final, _root=True):
"""Internal wrapper to hold a forward reference."""