-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[possibly-used-before-assignment] Model using assert_never (#9716)
Clarify "exact same test" exception
- Loading branch information
1 parent
3f1f7b8
commit 2879d0e
Showing
1 changed file
with
41 additions
and
7 deletions.
There are no files selected for viewing
48 changes: 41 additions & 7 deletions
48
doc/data/messages/p/possibly-used-before-assignment/details.rst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,49 @@ | ||
If you rely on a pattern like: | ||
You can use ``assert_never`` to mark exhaustive choices: | ||
|
||
.. sourcecode:: python | ||
|
||
from typing import assert_never | ||
|
||
def handle_date_suffix(suffix): | ||
if suffix == "d": | ||
... | ||
elif suffix == "m": | ||
... | ||
elif suffix == "y": | ||
... | ||
else: | ||
assert_never(suffix) | ||
|
||
if suffix in "dmy": | ||
handle_date_suffix(suffix) | ||
|
||
Pylint currently allows repeating the same test like this, even though this | ||
lets some error cases through, as pylint does not assess the intervening code: | ||
|
||
.. sourcecode:: python | ||
|
||
if guarded(): | ||
var = 1 | ||
|
||
# what if code here affects the result of guarded()? | ||
|
||
if guarded(): | ||
print(var) # emits possibly-used-before-assignment | ||
print(var) | ||
|
||
But this exception is limited to the repeating the exact same test. | ||
This warns: | ||
|
||
.. sourcecode:: python | ||
|
||
if guarded(): | ||
var = 1 | ||
|
||
if guarded() or other_condition: | ||
print(var) # [possibly-used-before-assignment] | ||
|
||
you may be concerned that ``possibly-used-before-assignment`` is not totally useful | ||
in this instance. However, consider that pylint, as a static analysis tool, does | ||
not know if ``guarded()`` is deterministic or talks to | ||
a database. (Likewise, for ``guarded`` instead of ``guarded()``, any other | ||
part of your program may have changed its value in the meantime.) | ||
If you find this surprising, consider that pylint, as a static analysis | ||
tool, does not know if ``guarded()`` is deterministic or talks to | ||
a database. For constants (e.g. ``guarded`` versus ``guarded()``), | ||
this is less of an issue, so in this case, | ||
``possibly-used-before-assignment`` acts more like a future-proofing style | ||
preference than an error, per se. |