Skip to content

Commit

Permalink
[possibly-used-before-assignment] Model using assert_never (#9716)
Browse files Browse the repository at this point in the history
Clarify "exact same test" exception
  • Loading branch information
jacobtylerwalls committed Jun 9, 2024
1 parent 3f1f7b8 commit 2879d0e
Showing 1 changed file with 41 additions and 7 deletions.
48 changes: 41 additions & 7 deletions doc/data/messages/p/possibly-used-before-assignment/details.rst
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.

0 comments on commit 2879d0e

Please sign in to comment.