diff options
author | Jelle Zijlstra <jelle.zijlstra@gmail.com> | 2022-03-17 03:02:26 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-03-17 03:02:26 (GMT) |
commit | 96568e995d840c66edb25b6b9d85e4dcccf5a936 (patch) | |
tree | 907a903c2807fb7437b4e5a5779d034609320a9f /Lib/typing.py | |
parent | 7c353b7594545fb9403b3123a17ad06cadc2f73d (diff) | |
download | cpython-96568e995d840c66edb25b6b9d85e4dcccf5a936.zip cpython-96568e995d840c66edb25b6b9d85e4dcccf5a936.tar.gz cpython-96568e995d840c66edb25b6b9d85e4dcccf5a936.tar.bz2 |
bpo-46480: add typing.assert_type (GH-30843)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: David Foster <david@dafoster.net>
Diffstat (limited to 'Lib/typing.py')
-rw-r--r-- | Lib/typing.py | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/Lib/typing.py b/Lib/typing.py index dd68e71..6930f5d 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -118,6 +118,7 @@ __all__ = [ # One-off things. 'AnyStr', + 'assert_type', 'assert_never', 'cast', 'final', @@ -2093,6 +2094,22 @@ def cast(typ, val): return val +def assert_type(val, typ, /): + """Assert (to the type checker) that the value is of the given type. + + When the type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # ok + assert_type(name, int) # type checker error + + At runtime this returns the first argument unchanged and otherwise + does nothing. + """ + return val + + _allowed_types = (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.ModuleType, WrapperDescriptorType, MethodWrapperType, MethodDescriptorType) |