Skip to content

Commit 3e7e50e

Browse files
[3.11] Improve assert_type phrasing (GH-104081) (#104084)
Improve assert_type phrasing (GH-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`. (cherry picked from commit 82ba6ce) Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
1 parent 0d40264 commit 3e7e50e

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

Diff for: Doc/library/typing.rst

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

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

2441-
When the type checker encounters a call to ``assert_type()``, it
2441+
At runtime this does nothing: it returns the first argument unchanged with no
2442+
checks or side effects, no matter the actual type of the argument.
2443+
2444+
When a static type checker encounters a call to ``assert_type()``, it
24422445
emits an error if the value is not of the specified type::
24432446

24442447
def greet(name: str) -> None:
24452448
assert_type(name, str) # OK, inferred type of `name` is `str`
24462449
assert_type(name, int) # type checker error
24472450

2448-
At runtime this returns the first argument unchanged with no side effects.
2449-
24502451
This function is useful for ensuring the type checker's understanding of a
24512452
script is in line with the developer's intentions::
24522453

Diff for: Lib/typing.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -2250,15 +2250,16 @@ def cast(typ, val):
22502250
def assert_type(val, typ, /):
22512251
"""Ask a static type checker to confirm that the value is of the given type.
22522252
2253-
When the type checker encounters a call to assert_type(), it
2253+
At runtime this does nothing: it returns the first argument unchanged with no
2254+
checks or side effects, no matter the actual type of the argument.
2255+
2256+
When a static type checker encounters a call to assert_type(), it
22542257
emits an error if the value is not of the specified type::
22552258
22562259
def greet(name: str) -> None:
22572260
assert_type(name, str) # ok
22582261
assert_type(name, int) # type checker error
22592262
2260-
At runtime this returns the first argument unchanged and otherwise
2261-
does nothing.
22622263
"""
22632264
return val
22642265

0 commit comments

Comments
 (0)