-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
variables.py
3414 lines (3092 loc) · 133 KB
/
variables.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
"""Variables checkers for Python code."""
from __future__ import annotations
import collections
import copy
import itertools
import math
import os
import re
from collections import defaultdict
from collections.abc import Generator, Iterable, Iterator
from enum import Enum
from functools import cached_property
from typing import TYPE_CHECKING, Any, NamedTuple
import astroid
import astroid.exceptions
from astroid import bases, extract_node, nodes, util
from astroid.nodes import _base_nodes
from astroid.typing import InferenceResult
from pylint.checkers import BaseChecker, utils
from pylint.checkers.utils import (
in_type_checking_block,
is_module_ignored,
is_postponed_evaluation_enabled,
is_sys_guard,
overridden_method,
)
from pylint.constants import TYPING_NEVER, TYPING_NORETURN
from pylint.interfaces import CONTROL_FLOW, HIGH, INFERENCE, INFERENCE_FAILURE
from pylint.typing import MessageDefinitionTuple
if TYPE_CHECKING:
from pylint.lint import PyLinter
SPECIAL_OBJ = re.compile("^_{2}[a-z]+_{2}$")
FUTURE = "__future__"
# regexp for ignored argument name
IGNORED_ARGUMENT_NAMES = re.compile("_.*|^ignored_|^unused_")
# In Python 3.7 abc has a Python implementation which is preferred
# by astroid. Unfortunately this also messes up our explicit checks
# for `abc`
METACLASS_NAME_TRANSFORMS = {"_py_abc": "abc"}
BUILTIN_RANGE = "builtins.range"
TYPING_MODULE = "typing"
TYPING_NAMES = frozenset(
{
"Any",
"Callable",
"ClassVar",
"Generic",
"Optional",
"Tuple",
"Type",
"TypeVar",
"Union",
"AbstractSet",
"ByteString",
"Container",
"ContextManager",
"Hashable",
"ItemsView",
"Iterable",
"Iterator",
"KeysView",
"Mapping",
"MappingView",
"MutableMapping",
"MutableSequence",
"MutableSet",
"Sequence",
"Sized",
"ValuesView",
"Awaitable",
"AsyncIterator",
"AsyncIterable",
"Coroutine",
"Collection",
"AsyncGenerator",
"AsyncContextManager",
"Reversible",
"SupportsAbs",
"SupportsBytes",
"SupportsComplex",
"SupportsFloat",
"SupportsInt",
"SupportsRound",
"Counter",
"Deque",
"Dict",
"DefaultDict",
"List",
"Set",
"FrozenSet",
"NamedTuple",
"Generator",
"AnyStr",
"Text",
"Pattern",
"BinaryIO",
}
)
DICT_TYPES = (
astroid.objects.DictValues,
astroid.objects.DictKeys,
astroid.objects.DictItems,
astroid.nodes.node_classes.Dict,
)
NODES_WITH_VALUE_ATTR = (
nodes.Assign,
nodes.AnnAssign,
nodes.AugAssign,
nodes.Expr,
nodes.Return,
nodes.Match,
nodes.TypeAlias,
)
class VariableVisitConsumerAction(Enum):
"""Reported by _check_consumer() and its sub-methods to determine the
subsequent action to take in _undefined_and_used_before_checker().
Continue -> continue loop to next consumer
Return -> return and thereby break the loop
"""
CONTINUE = 0
RETURN = 1
def _is_from_future_import(stmt: nodes.ImportFrom, name: str) -> bool | None:
"""Check if the name is a future import from another module."""
try:
module = stmt.do_import_module(stmt.modname)
except astroid.AstroidBuildingError:
return None
for local_node in module.locals.get(name, []):
if isinstance(local_node, nodes.ImportFrom) and local_node.modname == FUTURE:
return True
return None
def _get_unpacking_extra_info(node: nodes.Assign, inferred: InferenceResult) -> str:
"""Return extra information to add to the message for unpacking-non-sequence
and unbalanced-tuple/dict-unpacking errors.
"""
more = ""
if isinstance(inferred, DICT_TYPES):
if isinstance(node, nodes.Assign):
more = node.value.as_string()
elif isinstance(node, nodes.For):
more = node.iter.as_string()
return more
inferred_module = inferred.root().name
if node.root().name == inferred_module:
if node.lineno == inferred.lineno:
more = f"'{inferred.as_string()}'"
elif inferred.lineno:
more = f"defined at line {inferred.lineno}"
elif inferred.lineno:
more = f"defined at line {inferred.lineno} of {inferred_module}"
return more
def _detect_global_scope(
node: nodes.Name, frame: nodes.LocalsDictNodeNG, defframe: nodes.LocalsDictNodeNG
) -> bool:
"""Detect that the given frames share a global scope.
Two frames share a global scope when neither
of them are hidden under a function scope, as well
as any parent scope of them, until the root scope.
In this case, depending from something defined later on
will only work if guarded by a nested function definition.
Example:
class A:
# B has the same global scope as `C`, leading to a NameError.
# Return True to indicate a shared scope.
class B(C): ...
class C: ...
Whereas this does not lead to a NameError:
class A:
def guard():
# Return False to indicate no scope sharing.
class B(C): ...
class C: ...
"""
def_scope = scope = None
if frame and frame.parent:
scope = frame.parent.scope()
if defframe and defframe.parent:
def_scope = defframe.parent.scope()
if (
isinstance(frame, nodes.ClassDef)
and scope is not def_scope
and scope is utils.get_node_first_ancestor_of_type(node, nodes.FunctionDef)
):
# If the current node's scope is a class nested under a function,
# and the def_scope is something else, then they aren't shared.
return False
if isinstance(frame, nodes.FunctionDef):
# If the parent of the current node is a
# function, then it can be under its scope (defined in); or
# the `->` part of annotations. The same goes
# for annotations of function arguments, they'll have
# their parent the Arguments node.
if frame.parent_of(defframe):
return node.lineno < defframe.lineno # type: ignore[no-any-return]
if not isinstance(node.parent, (nodes.FunctionDef, nodes.Arguments)):
return False
break_scopes = []
for current_scope in (scope or frame, def_scope):
# Look for parent scopes. If there is anything different
# than a module or a class scope, then the frames don't
# share a global scope.
parent_scope = current_scope
while parent_scope:
if not isinstance(parent_scope, (nodes.ClassDef, nodes.Module)):
break_scopes.append(parent_scope)
break
if parent_scope.parent:
parent_scope = parent_scope.parent.scope()
else:
break
if len(set(break_scopes)) > 1:
# Store different scopes than expected.
# If the stored scopes are, in fact, the very same, then it means
# that the two frames (frame and defframe) share the same scope,
# and we could apply our lineno analysis over them.
# For instance, this works when they are inside a function, the node
# that uses a definition and the definition itself.
return False
# At this point, we are certain that frame and defframe share a scope
# and the definition of the first depends on the second.
return frame.lineno < defframe.lineno # type: ignore[no-any-return]
def _infer_name_module(node: nodes.Import, name: str) -> Generator[InferenceResult]:
context = astroid.context.InferenceContext()
context.lookupname = name
return node.infer(context, asname=False) # type: ignore[no-any-return]
def _fix_dot_imports(
not_consumed: dict[str, list[nodes.NodeNG]]
) -> list[tuple[str, _base_nodes.ImportNode]]:
"""Try to fix imports with multiple dots, by returning a dictionary
with the import names expanded.
The function unflattens root imports,
like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
and 'xml.sax' respectively.
"""
names: dict[str, _base_nodes.ImportNode] = {}
for name, stmts in not_consumed.items():
if any(
isinstance(stmt, nodes.AssignName)
and isinstance(stmt.assign_type(), nodes.AugAssign)
for stmt in stmts
):
continue
for stmt in stmts:
if not isinstance(stmt, (nodes.ImportFrom, nodes.Import)):
continue
for imports in stmt.names:
second_name = None
import_module_name = imports[0]
if import_module_name == "*":
# In case of wildcard imports,
# pick the name from inside the imported module.
second_name = name
else:
name_matches_dotted_import = False
if (
import_module_name.startswith(name)
and import_module_name.find(".") > -1
):
name_matches_dotted_import = True
if name_matches_dotted_import or name in imports:
# Most likely something like 'xml.etree',
# which will appear in the .locals as 'xml'.
# Only pick the name if it wasn't consumed.
second_name = import_module_name
if second_name and second_name not in names:
names[second_name] = stmt
return sorted(names.items(), key=lambda a: a[1].fromlineno)
def _find_frame_imports(name: str, frame: nodes.LocalsDictNodeNG) -> bool:
"""Detect imports in the frame, with the required *name*.
Such imports can be considered assignments if they are not globals.
Returns True if an import for the given name was found.
"""
if name in _flattened_scope_names(frame.nodes_of_class(nodes.Global)):
return False
imports = frame.nodes_of_class((nodes.Import, nodes.ImportFrom))
for import_node in imports:
for import_name, import_alias in import_node.names:
# If the import uses an alias, check only that.
# Otherwise, check only the import name.
if import_alias:
if import_alias == name:
return True
elif import_name and import_name == name:
return True
return False
def _import_name_is_global(
stmt: nodes.Global | _base_nodes.ImportNode, global_names: set[str]
) -> bool:
for import_name, import_alias in stmt.names:
# If the import uses an alias, check only that.
# Otherwise, check only the import name.
if import_alias:
if import_alias in global_names:
return True
elif import_name in global_names:
return True
return False
def _flattened_scope_names(
iterator: Iterator[nodes.Global | nodes.Nonlocal],
) -> set[str]:
values = (set(stmt.names) for stmt in iterator)
return set(itertools.chain.from_iterable(values))
def _assigned_locally(name_node: nodes.Name) -> bool:
"""Checks if name_node has corresponding assign statement in same scope."""
name_node_scope = name_node.scope()
assign_stmts = name_node_scope.nodes_of_class(nodes.AssignName)
return any(a.name == name_node.name for a in assign_stmts) or _find_frame_imports(
name_node.name, name_node_scope
)
def _has_locals_call_after_node(stmt: nodes.NodeNG, scope: nodes.FunctionDef) -> bool:
skip_nodes = (
nodes.FunctionDef,
nodes.ClassDef,
nodes.Import,
nodes.ImportFrom,
)
for call in scope.nodes_of_class(nodes.Call, skip_klass=skip_nodes):
inferred = utils.safe_infer(call.func)
if (
utils.is_builtin_object(inferred)
and getattr(inferred, "name", None) == "locals"
):
if stmt.lineno < call.lineno:
return True
return False
MSGS: dict[str, MessageDefinitionTuple] = {
"E0601": (
"Using variable %r before assignment",
"used-before-assignment",
"Emitted when a local variable is accessed before its assignment took place. "
"Assignments in try blocks are assumed not to have occurred when evaluating "
"associated except/finally blocks. Assignments in except blocks are assumed "
"not to have occurred when evaluating statements outside the block, except "
"when the associated try block contains a return statement.",
),
"E0602": (
"Undefined variable %r",
"undefined-variable",
"Used when an undefined variable is accessed.",
),
"E0603": (
"Undefined variable name %r in __all__",
"undefined-all-variable",
"Used when an undefined variable name is referenced in __all__.",
),
"E0604": (
"Invalid object %r in __all__, must contain only strings",
"invalid-all-object",
"Used when an invalid (non-string) object occurs in __all__.",
),
"E0605": (
"Invalid format for __all__, must be tuple or list",
"invalid-all-format",
"Used when __all__ has an invalid format.",
),
"E0606": (
"Possibly using variable %r before assignment",
"possibly-used-before-assignment",
"Emitted when a local variable is accessed before its assignment took place "
"in both branches of an if/else switch.",
),
"E0611": (
"No name %r in module %r",
"no-name-in-module",
"Used when a name cannot be found in a module.",
),
"W0601": (
"Global variable %r undefined at the module level",
"global-variable-undefined",
'Used when a variable is defined through the "global" statement '
"but the variable is not defined in the module scope.",
),
"W0602": (
"Using global for %r but no assignment is done",
"global-variable-not-assigned",
"When a variable defined in the global scope is modified in an inner scope, "
"the 'global' keyword is required in the inner scope only if there is an "
"assignment operation done in the inner scope.",
),
"W0603": (
"Using the global statement", # W0121
"global-statement",
'Used when you use the "global" statement to update a global '
"variable. Pylint discourages its usage. That doesn't mean you cannot "
"use it!",
),
"W0604": (
"Using the global statement at the module level", # W0103
"global-at-module-level",
'Used when you use the "global" statement at the module level '
"since it has no effect.",
),
"W0611": (
"Unused %s",
"unused-import",
"Used when an imported module or variable is not used.",
),
"W0612": (
"Unused variable %r",
"unused-variable",
"Used when a variable is defined but not used.",
),
"W0613": (
"Unused argument %r",
"unused-argument",
"Used when a function or method argument is not used.",
),
"W0614": (
"Unused import(s) %s from wildcard import of %s",
"unused-wildcard-import",
"Used when an imported module or variable is not used from a "
"`'from X import *'` style import.",
),
"W0621": (
"Redefining name %r from outer scope (line %s)",
"redefined-outer-name",
"Used when a variable's name hides a name defined in an outer scope or except handler.",
),
"W0622": (
"Redefining built-in %r",
"redefined-builtin",
"Used when a variable or function override a built-in.",
),
"W0631": (
"Using possibly undefined loop variable %r",
"undefined-loop-variable",
"Used when a loop variable (i.e. defined by a for loop or "
"a list comprehension or a generator expression) is used outside "
"the loop.",
),
"W0632": (
"Possible unbalanced tuple unpacking with sequence %s: left side has %d "
"label%s, right side has %d value%s",
"unbalanced-tuple-unpacking",
"Used when there is an unbalanced tuple unpacking in assignment",
{"old_names": [("E0632", "old-unbalanced-tuple-unpacking")]},
),
"E0633": (
"Attempting to unpack a non-sequence%s",
"unpacking-non-sequence",
"Used when something which is not a sequence is used in an unpack assignment",
{"old_names": [("W0633", "old-unpacking-non-sequence")]},
),
"W0640": (
"Cell variable %s defined in loop",
"cell-var-from-loop",
"A variable used in a closure is defined in a loop. "
"This will result in all closures using the same value for "
"the closed-over variable.",
),
"W0641": (
"Possibly unused variable %r",
"possibly-unused-variable",
"Used when a variable is defined but might not be used. "
"The possibility comes from the fact that locals() might be used, "
"which could consume or not the said variable",
),
"W0642": (
"Invalid assignment to %s in method",
"self-cls-assignment",
"Invalid assignment to self or cls in instance or class method "
"respectively.",
),
"E0643": (
"Invalid index for iterable length",
"potential-index-error",
"Emitted when an index used on an iterable goes beyond the length of that "
"iterable.",
),
"W0644": (
"Possible unbalanced dict unpacking with %s: "
"left side has %d label%s, right side has %d value%s",
"unbalanced-dict-unpacking",
"Used when there is an unbalanced dict unpacking in assignment or for loop",
),
}
class ScopeConsumer(NamedTuple):
"""Store nodes and their consumption states."""
to_consume: dict[str, list[nodes.NodeNG]]
consumed: dict[str, list[nodes.NodeNG]]
consumed_uncertain: defaultdict[str, list[nodes.NodeNG]]
scope_type: str
class NamesConsumer:
"""A simple class to handle consumed, to consume and scope type info of node locals."""
def __init__(self, node: nodes.NodeNG, scope_type: str) -> None:
self._atomic = ScopeConsumer(
copy.copy(node.locals), {}, collections.defaultdict(list), scope_type
)
self.node = node
self.names_under_always_false_test: set[str] = set()
self.names_defined_under_one_branch_only: set[str] = set()
def __repr__(self) -> str:
_to_consumes = [f"{k}->{v}" for k, v in self._atomic.to_consume.items()]
_consumed = [f"{k}->{v}" for k, v in self._atomic.consumed.items()]
_consumed_uncertain = [
f"{k}->{v}" for k, v in self._atomic.consumed_uncertain.items()
]
to_consumes = ", ".join(_to_consumes)
consumed = ", ".join(_consumed)
consumed_uncertain = ", ".join(_consumed_uncertain)
return f"""
to_consume : {to_consumes}
consumed : {consumed}
consumed_uncertain: {consumed_uncertain}
scope_type : {self._atomic.scope_type}
"""
def __iter__(self) -> Iterator[Any]:
return iter(self._atomic)
@property
def to_consume(self) -> dict[str, list[nodes.NodeNG]]:
return self._atomic.to_consume
@property
def consumed(self) -> dict[str, list[nodes.NodeNG]]:
return self._atomic.consumed
@property
def consumed_uncertain(self) -> defaultdict[str, list[nodes.NodeNG]]:
"""Retrieves nodes filtered out by get_next_to_consume() that may not
have executed.
These include nodes such as statements in except blocks, or statements
in try blocks (when evaluating their corresponding except and finally
blocks). Checkers that want to treat the statements as executed
(e.g. for unused-variable) may need to add them back.
"""
return self._atomic.consumed_uncertain
@property
def scope_type(self) -> str:
return self._atomic.scope_type
def mark_as_consumed(self, name: str, consumed_nodes: list[nodes.NodeNG]) -> None:
"""Mark the given nodes as consumed for the name.
If all of the nodes for the name were consumed, delete the name from
the to_consume dictionary
"""
unconsumed = [n for n in self.to_consume[name] if n not in set(consumed_nodes)]
self.consumed[name] = consumed_nodes
if unconsumed:
self.to_consume[name] = unconsumed
else:
del self.to_consume[name]
def get_next_to_consume(self, node: nodes.Name) -> list[nodes.NodeNG] | None:
"""Return a list of the nodes that define `node` from this scope.
If it is uncertain whether a node will be consumed, such as for statements in
except blocks, add it to self.consumed_uncertain instead of returning it.
Return None to indicate a special case that needs to be handled by the caller.
"""
name = node.name
parent_node = node.parent
found_nodes = self.to_consume.get(name)
node_statement = node.statement()
if (
found_nodes
and isinstance(parent_node, nodes.Assign)
and parent_node == found_nodes[0].parent
):
lhs = found_nodes[0].parent.targets[0]
if (
isinstance(lhs, nodes.AssignName) and lhs.name == name
): # this name is defined in this very statement
found_nodes = None
if (
found_nodes
and isinstance(parent_node, nodes.For)
and parent_node.iter == node
and parent_node.target in found_nodes
):
found_nodes = None
# Before filtering, check that this node's name is not a nonlocal
if any(
isinstance(child, nodes.Nonlocal) and node.name in child.names
for child in node.frame().get_children()
):
return found_nodes
# And no comprehension is under the node's frame
if VariablesChecker._comprehension_between_frame_and_node(node):
return found_nodes
# Filter out assignments in ExceptHandlers that node is not contained in
if found_nodes:
found_nodes = [
n
for n in found_nodes
if not isinstance(n.statement(), nodes.ExceptHandler)
or n.statement().parent_of(node)
]
# Filter out assignments guarded by always false conditions
if found_nodes:
uncertain_nodes = self._uncertain_nodes_if_tests(found_nodes, node)
self.consumed_uncertain[node.name] += uncertain_nodes
uncertain_nodes_set = set(uncertain_nodes)
found_nodes = [n for n in found_nodes if n not in uncertain_nodes_set]
# Filter out assignments in an Except clause that the node is not
# contained in, assuming they may fail
if found_nodes:
uncertain_nodes = self._uncertain_nodes_in_except_blocks(
found_nodes, node, node_statement
)
self.consumed_uncertain[node.name] += uncertain_nodes
uncertain_nodes_set = set(uncertain_nodes)
found_nodes = [n for n in found_nodes if n not in uncertain_nodes_set]
# If this node is in a Finally block of a Try/Finally,
# filter out assignments in the try portion, assuming they may fail
if found_nodes:
uncertain_nodes = (
self._uncertain_nodes_in_try_blocks_when_evaluating_finally_blocks(
found_nodes, node_statement, name
)
)
self.consumed_uncertain[node.name] += uncertain_nodes
uncertain_nodes_set = set(uncertain_nodes)
found_nodes = [n for n in found_nodes if n not in uncertain_nodes_set]
# If this node is in an ExceptHandler,
# filter out assignments in the try portion, assuming they may fail
if found_nodes:
uncertain_nodes = (
self._uncertain_nodes_in_try_blocks_when_evaluating_except_blocks(
found_nodes, node_statement
)
)
self.consumed_uncertain[node.name] += uncertain_nodes
uncertain_nodes_set = set(uncertain_nodes)
found_nodes = [n for n in found_nodes if n not in uncertain_nodes_set]
return found_nodes
def _inferred_to_define_name_raise_or_return(
self, name: str, node: nodes.NodeNG
) -> bool:
"""Return True if there is a path under this `if_node`
that is inferred to define `name`, raise, or return.
"""
# Handle try and with
if isinstance(node, nodes.Try):
# Allow either a path through try/else/finally OR a path through ALL except handlers
try_except_node = node
if node.finalbody:
try_except_node = next(
(child for child in node.nodes_of_class(nodes.Try)),
None,
)
handlers = try_except_node.handlers if try_except_node else []
return NamesConsumer._defines_name_raises_or_returns_recursive(
name, node
) or all(
NamesConsumer._defines_name_raises_or_returns_recursive(name, handler)
for handler in handlers
)
if isinstance(node, (nodes.With, nodes.For, nodes.While)):
return NamesConsumer._defines_name_raises_or_returns_recursive(name, node)
if not isinstance(node, nodes.If):
return False
# Be permissive if there is a break or a continue
if any(node.nodes_of_class(nodes.Break, nodes.Continue)):
return True
# Is there an assignment in this node itself, e.g. in named expression?
if NamesConsumer._defines_name_raises_or_returns(name, node):
return True
test = node.test.value if isinstance(node.test, nodes.NamedExpr) else node.test
all_inferred = utils.infer_all(test)
only_search_if = False
only_search_else = True
for inferred in all_inferred:
if not isinstance(inferred, nodes.Const):
only_search_else = False
continue
val = inferred.value
only_search_if = only_search_if or (val != NotImplemented and val)
only_search_else = only_search_else and not val
# Only search else branch when test condition is inferred to be false
if all_inferred and only_search_else:
self.names_under_always_false_test.add(name)
return self._branch_handles_name(name, node.orelse)
# Search both if and else branches
if_branch_handles = self._branch_handles_name(name, node.body)
else_branch_handles = self._branch_handles_name(name, node.orelse)
if if_branch_handles ^ else_branch_handles:
self.names_defined_under_one_branch_only.add(name)
elif name in self.names_defined_under_one_branch_only:
self.names_defined_under_one_branch_only.remove(name)
return if_branch_handles and else_branch_handles
def _branch_handles_name(self, name: str, body: Iterable[nodes.NodeNG]) -> bool:
return any(
NamesConsumer._defines_name_raises_or_returns(name, if_body_stmt)
or isinstance(
if_body_stmt,
(
nodes.If,
nodes.Try,
nodes.With,
nodes.For,
nodes.While,
),
)
and self._inferred_to_define_name_raise_or_return(name, if_body_stmt)
for if_body_stmt in body
)
def _uncertain_nodes_if_tests(
self, found_nodes: list[nodes.NodeNG], node: nodes.NodeNG
) -> list[nodes.NodeNG]:
"""Identify nodes of uncertain execution because they are defined under if
tests.
Don't identify a node if there is a path that is inferred to
define the name, raise, or return (e.g. any executed if/elif/else branch).
"""
uncertain_nodes = []
for other_node in found_nodes:
if isinstance(other_node, nodes.AssignName):
name = other_node.name
elif isinstance(other_node, (nodes.Import, nodes.ImportFrom)):
name = node.name
else:
continue
all_if = [
n
for n in other_node.node_ancestors()
if isinstance(n, nodes.If) and not n.parent_of(node)
]
if not all_if:
continue
closest_if = all_if[0]
if (
isinstance(node, nodes.AssignName)
and node.frame() is not closest_if.frame()
):
continue
if closest_if.parent_of(node):
continue
outer_if = all_if[-1]
if NamesConsumer._node_guarded_by_same_test(node, outer_if):
continue
# Name defined in the if/else control flow
if self._inferred_to_define_name_raise_or_return(name, outer_if):
continue
uncertain_nodes.append(other_node)
return uncertain_nodes
@staticmethod
def _node_guarded_by_same_test(node: nodes.NodeNG, other_if: nodes.If) -> bool:
"""Identify if `node` is guarded by an equivalent test as `other_if`.
Two tests are equivalent if their string representations are identical
or if their inferred values consist only of constants and those constants
are identical, and the if test guarding `node` is not a Name.
"""
other_if_test_as_string = other_if.test.as_string()
other_if_test_all_inferred = utils.infer_all(other_if.test)
for ancestor in node.node_ancestors():
if not isinstance(ancestor, nodes.If):
continue
if ancestor.test.as_string() == other_if_test_as_string:
return True
if isinstance(ancestor.test, nodes.Name):
continue
all_inferred = utils.infer_all(ancestor.test)
if len(all_inferred) == len(other_if_test_all_inferred):
if any(
not isinstance(test, nodes.Const)
for test in (*all_inferred, *other_if_test_all_inferred)
):
continue
if {test.value for test in all_inferred} != {
test.value for test in other_if_test_all_inferred
}:
continue
return True
return False
@staticmethod
def _uncertain_nodes_in_except_blocks(
found_nodes: list[nodes.NodeNG],
node: nodes.NodeNG,
node_statement: _base_nodes.Statement,
) -> list[nodes.NodeNG]:
"""Return any nodes in ``found_nodes`` that should be treated as uncertain
because they are in an except block.
"""
uncertain_nodes = []
for other_node in found_nodes:
other_node_statement = other_node.statement()
# Only testing for statements in the except block of Try
closest_except_handler = utils.get_node_first_ancestor_of_type(
other_node_statement, nodes.ExceptHandler
)
if not closest_except_handler:
continue
# If the other node is in the same scope as this node, assume it executes
if closest_except_handler.parent_of(node):
continue
closest_try_except: nodes.Try = closest_except_handler.parent
# If the try or else blocks return, assume the except blocks execute.
try_block_returns = any(
isinstance(try_statement, nodes.Return)
for try_statement in closest_try_except.body
)
else_block_returns = any(
isinstance(else_statement, nodes.Return)
for else_statement in closest_try_except.orelse
)
else_block_exits = any(
isinstance(else_statement, nodes.Expr)
and isinstance(else_statement.value, nodes.Call)
and utils.is_terminating_func(else_statement.value)
for else_statement in closest_try_except.orelse
)
else_block_continues = any(
isinstance(else_statement, nodes.Continue)
for else_statement in closest_try_except.orelse
)
if (
else_block_continues
and isinstance(node_statement.parent, (nodes.For, nodes.While))
and closest_try_except.parent.parent_of(node_statement)
):
continue
if try_block_returns or else_block_returns or else_block_exits:
# Exception: if this node is in the final block of the other_node_statement,
# it will execute before returning. Assume the except statements are uncertain.
if (
isinstance(node_statement.parent, nodes.Try)
and node_statement in node_statement.parent.finalbody
and closest_try_except.parent.parent_of(node_statement)
):
uncertain_nodes.append(other_node)
# Or the node_statement is in the else block of the relevant Try
elif (
isinstance(node_statement.parent, nodes.Try)
and node_statement in node_statement.parent.orelse
and closest_try_except.parent.parent_of(node_statement)
):
uncertain_nodes.append(other_node)
# Assume the except blocks execute, so long as each handler
# defines the name, raises, or returns.
elif all(
NamesConsumer._defines_name_raises_or_returns_recursive(
node.name, handler
)
for handler in closest_try_except.handlers
):
continue
if NamesConsumer._check_loop_finishes_via_except(node, closest_try_except):
continue
# Passed all tests for uncertain execution
uncertain_nodes.append(other_node)
return uncertain_nodes
@staticmethod
def _defines_name_raises_or_returns(name: str, node: nodes.NodeNG) -> bool:
if isinstance(node, (nodes.Raise, nodes.Assert, nodes.Return, nodes.Continue)):
return True
if isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Call):
if utils.is_terminating_func(node.value):
return True
if (
isinstance(node.value.func, nodes.Name)
and node.value.func.name == "assert_never"
):
return True
if (
isinstance(node, nodes.AnnAssign)
and node.value
and isinstance(node.target, nodes.AssignName)
and node.target.name == name
):
return True
if isinstance(node, nodes.Assign):
for target in node.targets:
for elt in utils.get_all_elements(target):
if isinstance(elt, nodes.Starred):
elt = elt.value
if isinstance(elt, nodes.AssignName) and elt.name == name:
return True
if isinstance(node, nodes.If):
if any(
child_named_expr.target.name == name
for child_named_expr in node.nodes_of_class(nodes.NamedExpr)
):
return True
if isinstance(node, (nodes.Import, nodes.ImportFrom)) and any(
(node_name[1] and node_name[1] == name) or (node_name[0] == name)
for node_name in node.names
):
return True
if isinstance(node, nodes.With) and any(
isinstance(item[1], nodes.AssignName) and item[1].name == name
for item in node.items
):
return True
if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)) and node.name == name:
return True
if (
isinstance(node, nodes.ExceptHandler)
and node.name
and node.name.name == name
):
return True
return False
@staticmethod
def _defines_name_raises_or_returns_recursive(
name: str, node: nodes.NodeNG
) -> bool:
"""Return True if some child of `node` defines the name `name`,
raises, or returns.
"""
for stmt in node.get_children():
if NamesConsumer._defines_name_raises_or_returns(name, stmt):
return True
if isinstance(stmt, (nodes.If, nodes.With)):
if any(