summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorJelle Zijlstra <jelle.zijlstra@gmail.com>2022-03-17 03:02:26 (GMT)
committerGitHub <noreply@github.com>2022-03-17 03:02:26 (GMT)
commit96568e995d840c66edb25b6b9d85e4dcccf5a936 (patch)
tree907a903c2807fb7437b4e5a5779d034609320a9f /Doc
parent7c353b7594545fb9403b3123a17ad06cadc2f73d (diff)
downloadcpython-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 'Doc')
-rw-r--r--Doc/library/typing.rst25
1 files changed, 25 insertions, 0 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index c7c2cd6..57979cb 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -2148,6 +2148,31 @@ Functions and decorators
runtime we intentionally don't check anything (we want this
to be as fast as possible).
+.. function:: assert_type(val, typ, /)
+
+ Assert (to the type checker) that *val* has an inferred type of *typ*.
+
+ 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, inferred type of `name` is `str`
+ assert_type(name, int) # type checker error
+
+ At runtime this returns the first argument unchanged with no side effects.
+
+ This function is useful for ensuring the type checker's understanding of a
+ script is in line with the developer's intentions::
+
+ def complex_function(arg: object):
+ # Do some complex type-narrowing logic,
+ # after which we hope the inferred type will be `int`
+ ...
+ # Test whether the type checker correctly understands our function
+ assert_type(arg, int)
+
+ .. versionadded:: 3.11
+
.. function:: assert_never(arg, /)
Assert to the type checker that a line of code is unreachable.