Skip to content

Commit 7ceacc8

Browse files
emmatypinggvanrossum
authored andcommitted
add cast example for Py2 cheat sheet (#2549)
The same example I wrote for the Py3 cheat sheet. Fixes #1662.
1 parent 382062a commit 7ceacc8

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

docs/source/cheat_sheet.rst

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ When you're puzzled or when things are complicated
106106

107107
.. code-block:: python
108108
109-
from typing import Union, Any
109+
from typing import Union, Any, cast
110110
111111
# To find out what type mypy infers for an expression anywhere in
112112
# your program, wrap it in reveal_type. Mypy will print an error
@@ -134,7 +134,13 @@ When you're puzzled or when things are complicated
134134
# (in mypy, typeshed, or your own code) or an explanation of the issue.
135135
x = confusing_function() # type: ignore # https://github.com/python/mypy/issues/1167
136136
137-
# TODO: explain cast
137+
# cast is a helper function for mypy that allows for guidance of how to convert types.
138+
# it does not cast at runtime
139+
a = [4]
140+
b = cast(List[int], a) # passes fine
141+
c = cast(List[str], a) # passes fine (no runtime check)
142+
reveal_type(c) # -> error: Revealed type is 'builtins.list[builtins.str]'
143+
print(c) # -> [4] the object is not cast
138144
139145
# TODO: explain "Need type annotation for variable" when
140146
# initializing with None or an empty container

0 commit comments

Comments
 (0)