Skip to content

Commit 82ba6ce

Browse files
authored
Improve assert_type phrasing (#104081)
I'd like to make the fact that this does nothing at runtime really obvious, since I suspect this is unintuitive for users who are unfamiliar with static type checking. I thought of this because of https://discuss.python.org/t/add-arg-check-type-to-types/26384 wherein I'm skeptical that the user really did want `assert_type`.
1 parent f0ad456 commit 82ba6ce

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

Doc/library/typing.rst

+4-3
Original file line numberDiff line numberDiff line change
@@ -2484,15 +2484,16 @@ Functions and decorators
24842484

24852485
Ask a static type checker to confirm that *val* has an inferred type of *typ*.
24862486

2487-
When the type checker encounters a call to ``assert_type()``, it
2487+
At runtime this does nothing: it returns the first argument unchanged with no
2488+
checks or side effects, no matter the actual type of the argument.
2489+
2490+
When a static type checker encounters a call to ``assert_type()``, it
24882491
emits an error if the value is not of the specified type::
24892492

24902493
def greet(name: str) -> None:
24912494
assert_type(name, str) # OK, inferred type of `name` is `str`
24922495
assert_type(name, int) # type checker error
24932496

2494-
At runtime this returns the first argument unchanged with no side effects.
2495-
24962497
This function is useful for ensuring the type checker's understanding of a
24972498
script is in line with the developer's intentions::
24982499

Lib/typing.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -2319,15 +2319,16 @@ def cast(typ, val):
23192319
def assert_type(val, typ, /):
23202320
"""Ask a static type checker to confirm that the value is of the given type.
23212321
2322-
When the type checker encounters a call to assert_type(), it
2322+
At runtime this does nothing: it returns the first argument unchanged with no
2323+
checks or side effects, no matter the actual type of the argument.
2324+
2325+
When a static type checker encounters a call to assert_type(), it
23232326
emits an error if the value is not of the specified type::
23242327
23252328
def greet(name: str) -> None:
23262329
assert_type(name, str) # ok
23272330
assert_type(name, int) # type checker error
23282331
2329-
At runtime this returns the first argument unchanged and otherwise
2330-
does nothing.
23312332
"""
23322333
return val
23332334

0 commit comments

Comments
 (0)