Skip to content

Commit 2879d0e

Browse files
[possibly-used-before-assignment] Model using assert_never (#9716)
Clarify "exact same test" exception
1 parent 3f1f7b8 commit 2879d0e

File tree

1 file changed

+41
-7
lines changed
  • doc/data/messages/p/possibly-used-before-assignment

1 file changed

+41
-7
lines changed
Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,49 @@
1-
If you rely on a pattern like:
1+
You can use ``assert_never`` to mark exhaustive choices:
2+
3+
.. sourcecode:: python
4+
5+
from typing import assert_never
6+
7+
def handle_date_suffix(suffix):
8+
if suffix == "d":
9+
...
10+
elif suffix == "m":
11+
...
12+
elif suffix == "y":
13+
...
14+
else:
15+
assert_never(suffix)
16+
17+
if suffix in "dmy":
18+
handle_date_suffix(suffix)
19+
20+
Pylint currently allows repeating the same test like this, even though this
21+
lets some error cases through, as pylint does not assess the intervening code:
222

323
.. sourcecode:: python
424

525
if guarded():
626
var = 1
727

28+
# what if code here affects the result of guarded()?
29+
830
if guarded():
9-
print(var) # emits possibly-used-before-assignment
31+
print(var)
32+
33+
But this exception is limited to the repeating the exact same test.
34+
This warns:
35+
36+
.. sourcecode:: python
37+
38+
if guarded():
39+
var = 1
40+
41+
if guarded() or other_condition:
42+
print(var) # [possibly-used-before-assignment]
1043

11-
you may be concerned that ``possibly-used-before-assignment`` is not totally useful
12-
in this instance. However, consider that pylint, as a static analysis tool, does
13-
not know if ``guarded()`` is deterministic or talks to
14-
a database. (Likewise, for ``guarded`` instead of ``guarded()``, any other
15-
part of your program may have changed its value in the meantime.)
44+
If you find this surprising, consider that pylint, as a static analysis
45+
tool, does not know if ``guarded()`` is deterministic or talks to
46+
a database. For constants (e.g. ``guarded`` versus ``guarded()``),
47+
this is less of an issue, so in this case,
48+
``possibly-used-before-assignment`` acts more like a future-proofing style
49+
preference than an error, per se.

0 commit comments

Comments
 (0)