|
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: |
2 | 22 |
|
3 | 23 | .. sourcecode:: python
|
4 | 24 |
|
5 | 25 | if guarded():
|
6 | 26 | var = 1
|
7 | 27 |
|
| 28 | + # what if code here affects the result of guarded()? |
| 29 | + |
8 | 30 | 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] |
10 | 43 |
|
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