Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[possibly-used-before-assignment] Model using assert_never #9716

Merged
merged 4 commits into from
Jun 9, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 reuslt of guarded()?

Pierre-Sassoulas marked this conversation as resolved.
Show resolved Hide resolved
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.
Loading