Skip to content

Commit 9a3fa64

Browse files
vincent-przilevkivskyi
authored andcommitted
Complement cheatsheet for Optionals (#6074)
Fixes #5037 Add a paragrah to explain there are 2 ways to make the typechecker understand that an optional is not `None`: use a if condition or an `assert`.
1 parent a7296c4 commit 9a3fa64

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

docs/source/cheat_sheet.rst

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,12 @@ Built-in types
4646
4747
# Use Optional[] for values that could be None
4848
x = some_function() # type: Optional[str]
49+
# Mypy understands a value can't be None in an if-statement
4950
if x is not None:
50-
print x
51-
51+
print x.upper()
52+
# If a value can never be None due to some invariants, use an assert
53+
assert x is not None
54+
print x.upper()
5255
5356
Functions
5457
*********

docs/source/cheat_sheet_py3.rst

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,12 @@ Built-in types
7272
7373
# Use Optional[] for values that could be None
7474
x: Optional[str] = some_function()
75+
# Mypy understands a value can't be None in an if-statement
7576
if x is not None:
76-
print(x)
77-
77+
print(x.upper())
78+
# If a value can never be None due to some invariants, use an assert
79+
assert x is not None
80+
print(x.upper())
7881
7982
Functions
8083
*********

0 commit comments

Comments
 (0)