Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pyflakes/checker.py: 88%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2Main module.
4Implement the central Checker class.
5Also, it models the Bindings and Scopes.
6"""
7import __future__
8import builtins
9import ast
10import collections
11import contextlib
12import functools
13import os
14import re
15import string
16import sys
17from collections.abc import Iterable
19from pyflakes import messages
21PYPY = hasattr(sys, 'pypy_version_info')
23builtin_vars = frozenset(dir(builtins)) | {
24 # Globally defined names which are not attributes of the builtins module, or
25 # are only present on some platforms.
26 '__file__', '__builtins__', '__annotations__', 'WindowsError'
27}
30@functools.cache
31def _custom_builtins() -> frozenset[str]:
32 var = os.environ.get('PYFLAKES_BUILTINS')
33 if var is not None:
34 return frozenset(var.split(','))
35 else:
36 return frozenset()
39parse_format_string = string.Formatter().parse
42@functools.cache
43def _doctest_parser():
44 import doctest
45 return doctest.DocTestParser().get_examples
48def getAlternatives(n):
49 if isinstance(n, ast.If):
50 return [n.body]
51 elif isinstance(n, ast.Try):
52 return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
53 elif isinstance(n, ast.Match):
54 return [mc.body for mc in n.cases]
57FOR_TYPES = (ast.For, ast.AsyncFor)
60def _is_singleton(node): # type: (ast.AST) -> bool
61 return (
62 isinstance(node, ast.Constant) and
63 isinstance(node.value, (bool, type(Ellipsis), type(None)))
64 )
67def _is_tuple_constant(node): # type: (ast.AST) -> bool
68 return (
69 isinstance(node, ast.Tuple) and
70 all(_is_constant(elt) for elt in node.elts)
71 )
74def _is_constant(node):
75 return isinstance(node, ast.Constant) or _is_tuple_constant(node)
78def _is_const_non_singleton(node): # type: (ast.AST) -> bool
79 return _is_constant(node) and not _is_singleton(node)
82def _is_name_or_attr(node, name): # type: (ast.AST, str) -> bool
83 return (
84 (isinstance(node, ast.Name) and node.id == name) or
85 (isinstance(node, ast.Attribute) and node.attr == name)
86 )
89MAPPING_KEY_RE = re.compile(r'\(([^()]*)\)')
90CONVERSION_FLAG_RE = re.compile('[#0+ -]*')
91WIDTH_RE = re.compile(r'(?:\*|\d*)')
92PRECISION_RE = re.compile(r'(?:\.(?:\*|\d*))?')
93LENGTH_RE = re.compile('[hlL]?')
94# https://docs.python.org/3/library/stdtypes.html#old-string-formatting
95VALID_CONVERSIONS = frozenset('diouxXeEfFgGcrsa%')
98def _must_match(regex, string, pos):
99 match = regex.match(string, pos)
100 assert match is not None
101 return match
104def parse_percent_format(s):
105 """Parses the string component of a `'...' % ...` format call
107 Copied from https://github.com/asottile/pyupgrade at v1.20.1
108 """
110 def _parse_inner():
111 string_start = 0
112 string_end = 0
113 in_fmt = False
115 i = 0
116 while i < len(s):
117 if not in_fmt:
118 try:
119 i = s.index('%', i)
120 except ValueError: # no more % fields!
121 yield s[string_start:], None
122 return
123 else:
124 string_end = i
125 i += 1
126 in_fmt = True
127 else:
128 key_match = MAPPING_KEY_RE.match(s, i)
129 if key_match:
130 key = key_match.group(1)
131 i = key_match.end()
132 else:
133 key = None
135 conversion_flag_match = _must_match(CONVERSION_FLAG_RE, s, i)
136 conversion_flag = conversion_flag_match.group() or None
137 i = conversion_flag_match.end()
139 width_match = _must_match(WIDTH_RE, s, i)
140 width = width_match.group() or None
141 i = width_match.end()
143 precision_match = _must_match(PRECISION_RE, s, i)
144 precision = precision_match.group() or None
145 i = precision_match.end()
147 # length modifier is ignored
148 i = _must_match(LENGTH_RE, s, i).end()
150 try:
151 conversion = s[i]
152 except IndexError:
153 raise ValueError('end-of-string while parsing format')
154 i += 1
156 fmt = (key, conversion_flag, width, precision, conversion)
157 yield s[string_start:string_end], fmt
159 in_fmt = False
160 string_start = i
162 if in_fmt:
163 raise ValueError('end-of-string while parsing format')
165 return tuple(_parse_inner())
168def iter_child_nodes(node, omit=None):
169 """
170 Yield all direct child nodes of *node*, that is, all fields that
171 are nodes and all items of fields that are lists of nodes.
173 :param node: AST node to be iterated upon
174 :param omit: String or tuple of strings denoting the
175 attributes of the node to be omitted from
176 further parsing
177 :param _fields_order: Order of AST node fields
178 """
179 for name in node.__class__._fields:
180 if omit and name in omit:
181 continue
182 field = getattr(node, name, None)
183 if isinstance(field, ast.AST):
184 yield field
185 elif isinstance(field, list):
186 for item in field:
187 if isinstance(item, ast.AST):
188 yield item
191def iter_dict_children(node: ast.Dict) -> Iterable[tuple[ast.AST, ast.AST]]:
192 return zip(node.keys, node.values)
195def convert_to_value(item):
196 if isinstance(item, ast.Constant):
197 return item.value
198 elif isinstance(item, ast.Tuple):
199 return tuple(convert_to_value(i) for i in item.elts)
200 elif isinstance(item, ast.Name):
201 return VariableKey(item=item)
202 else:
203 return UnhandledKeyType()
206def is_notimplemented_name_node(node):
207 return isinstance(node, ast.Name) and getNodeName(node) == 'NotImplemented'
210class Binding:
211 """
212 Represents the binding of a value to a name.
214 The checker uses this to keep track of which names have been bound and
215 which names have not. See L{Assignment} for a special type of binding that
216 is checked with stricter rules.
218 @ivar used: pair of (L{Scope}, node) indicating the scope and
219 the node that this binding was last used.
220 """
222 def __init__(self, name, source):
223 self.name = name
224 self.source = source
225 self.used = False
227 def __repr__(self): # pragma: no cover
228 return '<{} object {!r} from line {!r} at 0x{:x}>'.format(
229 self.__class__.__name__,
230 self.name,
231 self.source.lineno,
232 id(self),
233 )
235 def redefines(self, other):
236 return isinstance(other, Definition) and self.name == other.name
239class Definition(Binding):
240 """
241 A binding that defines a function or a class.
242 """
243 def redefines(self, other):
244 return (
245 super().redefines(other) or
246 (isinstance(other, Assignment) and self.name == other.name)
247 )
250class Builtin(Definition):
251 """A definition created for all Python builtins."""
253 def __init__(self, name):
254 super().__init__(name, None)
256 def __repr__(self): # pragma: no cover
257 return '<{} object {!r} at 0x{:x}>'.format(
258 self.__class__.__name__,
259 self.name,
260 id(self)
261 )
264class UnhandledKeyType:
265 """
266 A dictionary key of a type that we cannot or do not check for duplicates.
267 """
270class VariableKey:
271 """
272 A dictionary key which is a variable.
274 @ivar item: The variable AST object.
275 """
276 def __init__(self, item):
277 self.name = item.id
279 def __eq__(self, compare):
280 return (
281 compare.__class__ == self.__class__ and
282 compare.name == self.name
283 )
285 def __hash__(self):
286 return hash(self.name)
289class Importation(Definition):
290 """
291 A binding created by an import statement.
293 @ivar fullName: The complete name given to the import statement,
294 possibly including multiple dotted components.
295 @type fullName: C{str}
296 """
298 def __init__(self, name, source, full_name=None, *, is_lazy: int):
299 self.fullName = full_name or name
300 self.redefined = []
301 self.is_lazy = is_lazy
302 super().__init__(name, source)
304 def redefines(self, other):
305 if isinstance(other, SubmoduleImportation):
306 # See note in SubmoduleImportation about RedefinedWhileUnused
307 return self.fullName == other.fullName
308 return isinstance(other, Definition) and self.name == other.name
310 def _has_alias(self):
311 """Return whether importation needs an as clause."""
312 return not self.fullName.split('.')[-1] == self.name
314 @property
315 def _lazy_s(self) -> str:
316 return 'lazy ' if self.is_lazy else ''
318 @property
319 def _alias_s(self) -> str:
320 return f' as {self.name}' if self._has_alias() else ''
322 @property
323 def source_statement(self):
324 """Generate a source statement equivalent to the import."""
325 return f'{self._lazy_s}import {self.fullName}{self._alias_s}'
327 @property
328 def imported_name(self):
329 """Return import full name with alias."""
330 return f'{self.fullName}{self._alias_s}'
333class SubmoduleImportation(Importation):
334 """
335 A binding created by a submodule import statement.
337 A submodule import is a special case where the root module is implicitly
338 imported, without an 'as' clause, and the submodule is also imported.
339 Python does not restrict which attributes of the root module may be used.
341 This class is only used when the submodule import is without an 'as' clause.
343 pyflakes handles this case by registering the root module name in the scope,
344 allowing any attribute of the root module to be accessed.
346 RedefinedWhileUnused is suppressed in `redefines` unless the submodule
347 name is also the same, to avoid false positives.
348 """
350 def __init__(self, name, source, *, is_lazy: int):
351 # A dot should only appear in the name when it is a submodule import
352 assert '.' in name and (not source or isinstance(source, ast.Import))
353 package_name = name.split('.')[0]
354 super().__init__(package_name, source, is_lazy=is_lazy)
355 self.fullName = name
357 def redefines(self, other):
358 if isinstance(other, Importation):
359 return self.fullName == other.fullName
360 return super().redefines(other)
362 @property
363 def source_statement(self):
364 return f'{self._lazy_s}import {self.fullName}'
366 @property
367 def imported_name(self):
368 return self.fullName
371class ImportationFrom(Importation):
373 def __init__(self, name, source, module, real_name=None, *, is_lazy: int):
374 self.module = module
375 self.real_name = real_name or name
377 if module.endswith('.'):
378 full_name = module + self.real_name
379 else:
380 full_name = module + '.' + self.real_name
382 super().__init__(name, source, full_name, is_lazy=is_lazy)
384 @property
385 def source_statement(self):
386 return f'{self._lazy_s}from {self.module} import {self.real_name}{self._alias_s}'
388 @property
389 def imported_name(self):
390 """Return import full name with alias."""
391 return f'{self.fullName}{self._alias_s}'
394class StarImportation(Importation):
395 """A binding created by a 'from x import *' statement."""
397 def __init__(self, name, source):
398 super().__init__('*', source, is_lazy=False)
399 # Each star importation needs a unique name, and
400 # may not be the module name otherwise it will be deemed imported
401 self.name = name + '.*'
402 self.fullName = name
404 @property
405 def source_statement(self):
406 return f'from {self.fullName} import *'
408 @property
409 def imported_name(self):
410 # When the module ends with a ., avoid the ambiguous '..*'
411 if self.fullName.endswith('.'):
412 return self.source_statement
413 else:
414 return self.name
417class FutureImportation(ImportationFrom):
418 """
419 A binding created by a from `__future__` import statement.
421 `__future__` imports are implicitly used.
422 """
424 def __init__(self, name, source, scope):
425 super().__init__(name, source, '__future__', is_lazy=False)
426 self.used = (scope, source)
429class Argument(Binding):
430 """
431 Represents binding a name as an argument.
432 """
435class Assignment(Binding):
436 """
437 Represents binding a name with an explicit assignment.
439 The checker will raise warnings for any Assignment that isn't used. Also,
440 the checker does not consider assignments in tuple/list unpacking to be
441 Assignments, rather it treats them as simple Bindings.
442 """
445class NamedExprAssignment(Assignment):
446 """
447 Represents binding a name with an assignment expression.
448 """
451class Annotation(Binding):
452 """
453 Represents binding a name to a type without an associated value.
455 As long as this name is not assigned a value in another binding, it is considered
456 undefined for most purposes. One notable exception is using the name as a type
457 annotation.
458 """
460 def redefines(self, other):
461 """An Annotation doesn't define any name, so it cannot redefine one."""
462 return False
465class FunctionDefinition(Definition):
466 pass
469class ClassDefinition(Definition):
470 pass
473class ExportBinding(Binding):
474 """
475 A binding created by an C{__all__} assignment. If the names in the list
476 can be determined statically, they will be treated as names for export and
477 additional checking applied to them.
479 The only recognized C{__all__} assignment via list/tuple concatenation is in the
480 following format:
482 __all__ = ['a'] + ['b'] + ['c']
484 Names which are imported and not otherwise used but appear in the value of
485 C{__all__} will not have an unused import warning reported for them.
486 """
488 def __init__(self, name, source, scope):
489 if '__all__' in scope and isinstance(source, ast.AugAssign):
490 self.names = list(scope['__all__'].names)
491 else:
492 self.names = []
494 def _add_to_names(container):
495 for node in container.elts:
496 if isinstance(node, ast.Constant) and isinstance(node.value, str):
497 self.names.append(node.value)
499 if isinstance(source.value, (ast.List, ast.Tuple)):
500 _add_to_names(source.value)
501 # If concatenating lists or tuples
502 elif isinstance(source.value, ast.BinOp):
503 currentValue = source.value
504 while isinstance(currentValue.right, (ast.List, ast.Tuple)):
505 left = currentValue.left
506 right = currentValue.right
507 _add_to_names(right)
508 # If more lists are being added
509 if isinstance(left, ast.BinOp):
510 currentValue = left
511 # If just two lists are being added
512 elif isinstance(left, (ast.List, ast.Tuple)):
513 _add_to_names(left)
514 # All lists accounted for - done
515 break
516 # If not list concatenation
517 else:
518 break
519 super().__init__(name, source)
522class Scope(dict):
523 importStarred = False # set to True when import * is found
525 def __repr__(self): # pragma: no cover
526 scope_cls = self.__class__.__name__
527 return f'<{scope_cls} at 0x{id(self):x} {dict.__repr__(self)}>'
530class ClassScope(Scope):
531 def __init__(self):
532 super().__init__()
533 # {name: node}
534 self.indirect_assignments = {}
537class FunctionScope(Scope):
538 """
539 I represent a name scope for a function.
541 @ivar globals: Names declared 'global' in this function.
542 """
543 usesLocals = False
544 always_used = frozenset((
545 '__tracebackhide__', '__traceback_info__',
546 '__traceback_supplement__', '__debuggerskip__',
547 ))
549 def __init__(self):
550 super().__init__()
551 # {name: node}
552 self.indirect_assignments = {}
554 def unused_assignments(self):
555 """
556 Return a generator for the assignments which have not been used.
557 """
558 for name, binding in self.items():
559 if (not binding.used and
560 name != '_' and # see issue #202
561 name not in self.always_used and
562 not self.usesLocals and
563 isinstance(binding, Assignment)):
564 yield name, binding
566 def unused_annotations(self):
567 """
568 Return a generator for the annotations which have not been used.
569 """
570 for name, binding in self.items():
571 if not binding.used and isinstance(binding, Annotation):
572 yield name, binding
575class TypeScope(Scope):
576 pass
579class ComprehensionScope(Scope):
580 pass
583class GeneratorScope(ComprehensionScope):
584 pass
587class ModuleScope(Scope):
588 """Scope for a module."""
589 _futures_allowed = True
590 _annotations_future_enabled = False
593class DoctestScope(ModuleScope):
594 """Scope for a doctest."""
597class DetectClassScopedMagic:
598 names = dir()
601def getNodeName(node):
602 # Returns node.id, or node.name, or None
603 if hasattr(node, 'id'): # One of the many nodes with an id
604 return node.id
605 if hasattr(node, 'name'): # an ExceptHandler node
606 return node.name
607 if hasattr(node, 'rest'): # a MatchMapping node
608 return node.rest
611TYPING_MODULES = frozenset(('typing', 'typing_extensions'))
614def _is_typing_helper(node, is_name_match_fn, scope_stack):
615 """
616 Internal helper to determine whether or not something is a member of a
617 typing module. This is used as part of working out whether we are within a
618 type annotation context.
620 Note: you probably don't want to use this function directly. Instead see the
621 utils below which wrap it (`_is_typing` and `_is_any_typing_member`).
622 """
624 def _bare_name_is_attr(name):
625 for scope in reversed(scope_stack):
626 if name in scope:
627 return (
628 isinstance(scope[name], ImportationFrom) and
629 scope[name].module in TYPING_MODULES and
630 is_name_match_fn(scope[name].real_name)
631 )
633 return False
635 def _module_scope_is_typing(name):
636 for scope in reversed(scope_stack):
637 if name in scope:
638 return (
639 isinstance(scope[name], Importation) and
640 scope[name].fullName in TYPING_MODULES
641 )
643 return False
645 return (
646 (
647 isinstance(node, ast.Name) and
648 _bare_name_is_attr(node.id)
649 ) or (
650 isinstance(node, ast.Attribute) and
651 isinstance(node.value, ast.Name) and
652 _module_scope_is_typing(node.value.id) and
653 is_name_match_fn(node.attr)
654 )
655 )
658def _is_typing(node, typing_attr, scope_stack):
659 """
660 Determine whether `node` represents the member of a typing module specified
661 by `typing_attr`.
663 This is used as part of working out whether we are within a type annotation
664 context.
665 """
666 return _is_typing_helper(node, lambda x: x == typing_attr, scope_stack)
669def _is_any_typing_member(node, scope_stack):
670 """
671 Determine whether `node` represents any member of a typing module.
673 This is used as part of working out whether we are within a type annotation
674 context.
675 """
676 return _is_typing_helper(node, lambda x: True, scope_stack)
679def is_typing_overload(value, scope_stack):
680 return (
681 isinstance(value.source, (ast.FunctionDef, ast.AsyncFunctionDef)) and
682 any(
683 _is_typing(dec, 'overload', scope_stack)
684 for dec in value.source.decorator_list
685 )
686 )
689class AnnotationState:
690 NONE = 0
691 STRING = 1
692 BARE = 2
695def in_annotation(func):
696 @functools.wraps(func)
697 def in_annotation_func(self, *args, **kwargs):
698 with self._enter_annotation():
699 return func(self, *args, **kwargs)
700 return in_annotation_func
703def in_string_annotation(func):
704 @functools.wraps(func)
705 def in_annotation_func(self, *args, **kwargs):
706 with self._enter_annotation(AnnotationState.STRING):
707 return func(self, *args, **kwargs)
708 return in_annotation_func
711class Checker:
712 """I check the cleanliness and sanity of Python code."""
714 _ast_node_scope = {
715 ast.Module: ModuleScope,
716 ast.ClassDef: ClassScope,
717 ast.FunctionDef: FunctionScope,
718 ast.AsyncFunctionDef: FunctionScope,
719 ast.Lambda: FunctionScope,
720 ast.ListComp: ComprehensionScope,
721 ast.SetComp: ComprehensionScope,
722 ast.GeneratorExp: GeneratorScope,
723 ast.DictComp: ComprehensionScope,
724 }
726 nodeDepth = 0
727 offset = None
728 _in_annotation = AnnotationState.NONE
730 def __init__(self, tree, filename='(none)', builtins=None,
731 withDoctest='PYFLAKES_DOCTEST' in os.environ):
732 self._nodeHandlers = {}
733 self._parents = {}
734 self._node_depths = {}
735 self._deferred = collections.deque()
736 self.deadScopes = []
737 self.messages = []
738 self.filename = filename
739 self.builtIns = builtin_vars | _custom_builtins()
740 if builtins:
741 self.builtIns = self.builtIns.union(builtins)
742 self.withDoctest = withDoctest
743 self.exceptHandlers = [()]
744 self.root = tree
746 self.scopeStack = []
748 self._running_deferred = False
750 scope_tp = Checker._ast_node_scope[type(tree)]
751 with self.in_scope(scope_tp):
752 for builtin in self.builtIns:
753 self.addBinding(None, Builtin(builtin))
754 self.handleChildren(tree)
755 self._run_deferred()
757 self.checkDeadScopes()
759 def deferFunction(self, callable):
760 """
761 Schedule a function handler to be called just before completion.
763 This is used for handling function bodies, which must be deferred
764 because code later in the file might modify the global scope. When
765 `callable` is called, the scope at the time this is called will be
766 restored, however it will contain any new bindings added to it.
767 """
768 self._deferred.append((callable, self.scopeStack[:], self.offset))
770 def _run_deferred(self):
771 self._running_deferred = True
773 orig = (self.scopeStack, self.offset)
775 while self._deferred:
776 handler, scope, offset = self._deferred.popleft()
777 self.scopeStack, self.offset = scope, offset
778 handler()
780 self.scopeStack, self.offset = orig
782 def _in_doctest(self):
783 return (len(self.scopeStack) >= 2 and
784 isinstance(self.scopeStack[1], DoctestScope))
786 @property
787 def futuresAllowed(self):
788 return (
789 isinstance(self.scope, ModuleScope) and
790 self.scope._futures_allowed
791 )
793 @futuresAllowed.setter
794 def futuresAllowed(self, value):
795 assert value is False
796 if isinstance(self.scope, ModuleScope):
797 self.scope._futures_allowed = False
799 @property
800 def annotationsFutureEnabled(self):
801 scope = self.scopeStack[0]
802 return isinstance(scope, ModuleScope) and scope._annotations_future_enabled
804 @annotationsFutureEnabled.setter
805 def annotationsFutureEnabled(self, value):
806 assert value is True
807 assert isinstance(self.scope, ModuleScope)
808 self.scope._annotations_future_enabled = True
810 @property
811 def scope(self):
812 return self.scopeStack[-1]
814 @contextlib.contextmanager
815 def in_scope(self, cls):
816 self.scopeStack.append(cls())
817 try:
818 yield
819 finally:
820 self.deadScopes.append(self.scopeStack.pop())
822 def checkDeadScopes(self):
823 """
824 Look at scopes which have been fully examined and report names in them
825 which were imported but unused.
826 """
827 for scope in self.deadScopes:
828 if isinstance(scope, (ClassScope, FunctionScope)):
829 for name, node in scope.indirect_assignments.items():
830 self.report(messages.UnusedIndirectAssignment, node, name)
832 # imports in classes are public members
833 if isinstance(scope, ClassScope):
834 continue
836 if isinstance(scope, FunctionScope):
837 for name, binding in scope.unused_assignments():
838 self.report(messages.UnusedVariable, binding.source, name)
839 for name, binding in scope.unused_annotations():
840 self.report(messages.UnusedAnnotation, binding.source, name)
842 all_binding = scope.get('__all__')
843 if all_binding and not isinstance(all_binding, ExportBinding):
844 all_binding = None
846 if all_binding:
847 all_names = set(all_binding.names)
848 undefined = [
849 name for name in all_binding.names
850 if name not in scope
851 ]
852 else:
853 all_names = undefined = []
855 if undefined:
856 if not scope.importStarred and \
857 os.path.basename(self.filename) != '__init__.py':
858 # Look for possible mistakes in the export list
859 for name in undefined:
860 self.report(messages.UndefinedExport,
861 scope['__all__'].source, name)
863 # mark all import '*' as used by the undefined in __all__
864 if scope.importStarred:
865 from_list = []
866 for binding in scope.values():
867 if isinstance(binding, StarImportation):
868 binding.used = all_binding
869 from_list.append(binding.fullName)
870 # report * usage, with a list of possible sources
871 from_list = ', '.join(sorted(from_list))
872 for name in undefined:
873 self.report(messages.ImportStarUsage,
874 scope['__all__'].source, name, from_list)
876 # Look for imported names that aren't used.
877 for value in scope.values():
878 if isinstance(value, Importation):
879 if not value.used and value.name not in all_names:
880 self.report(
881 messages.UnusedImport,
882 value.source, value.imported_name
883 )
884 for node in value.redefined:
885 self.report(
886 messages.RedefinedWhileUnused,
887 node, value.name, value.source,
888 )
890 def report(self, messageClass, *args, **kwargs):
891 self.messages.append(messageClass(self.filename, *args, **kwargs))
893 def getParent(self, node):
894 # Lookup the first parent which is not Tuple, List or Starred
895 while True:
896 node = self._parents[node]
897 if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
898 return node
900 def getCommonAncestor(self, lnode, rnode, stop):
901 if (
902 stop in (lnode, rnode) or
903 not (lnode in self._parents and rnode in self._parents)
904 ):
905 return None
906 if lnode is rnode:
907 return lnode
909 if self._node_depths[lnode] > self._node_depths[rnode]:
910 return self.getCommonAncestor(self._parents[lnode], rnode, stop)
911 if self._node_depths[lnode] < self._node_depths[rnode]:
912 return self.getCommonAncestor(lnode, self._parents[rnode], stop)
913 return self.getCommonAncestor(
914 self._parents[lnode],
915 self._parents[rnode],
916 stop,
917 )
919 def descendantOf(self, node, ancestors, stop):
920 for a in ancestors:
921 if self.getCommonAncestor(node, a, stop):
922 return True
923 return False
925 def differentForks(self, lnode, rnode):
926 """True, if lnode and rnode are located on different forks of IF/TRY"""
927 ancestor = self.getCommonAncestor(lnode, rnode, self.root)
928 parts = getAlternatives(ancestor)
929 if parts:
930 for items in parts:
931 if self.descendantOf(lnode, items, ancestor) ^ \
932 self.descendantOf(rnode, items, ancestor):
933 return True
934 return False
936 def addBinding(self, node, value):
937 """
938 Called when a binding is altered.
940 - `node` is the statement responsible for the change
941 - `value` is the new value, a Binding instance
942 """
943 # assert value.source in (node, self._parents[node]):
944 for scope in reversed(self.scopeStack):
945 if value.name in scope:
946 break
947 existing = scope.get(value.name)
949 if (existing and not isinstance(existing, Builtin) and
950 not self.differentForks(node, existing.source)):
952 parent_stmt = self.getParent(value.source)
953 if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
954 self.report(messages.ImportShadowedByLoopVar,
955 node, value.name, existing.source)
957 elif scope is self.scope:
958 if (
959 (not existing.used and value.redefines(existing)) and
960 (value.name != '_' or isinstance(existing, Importation)) and
961 not is_typing_overload(existing, self.scopeStack)
962 ):
963 self.report(messages.RedefinedWhileUnused,
964 node, value.name, existing.source)
966 if isinstance(scope, (ClassScope, FunctionScope)):
967 scope.indirect_assignments.pop(value.name, None)
969 elif isinstance(existing, Importation) and value.redefines(existing):
970 existing.redefined.append(node)
972 if value.name in self.scope:
973 # then assume the rebound name is used as a global or within a loop
974 value.used = self.scope[value.name].used
976 # don't treat annotations as assignments if there is an existing value
977 # in scope
978 if value.name not in self.scope or not isinstance(value, Annotation):
979 if isinstance(value, NamedExprAssignment):
980 # PEP 572: use scope in which outermost generator is defined
981 scope = next(
982 scope
983 for scope in reversed(self.scopeStack)
984 if not isinstance(scope, ComprehensionScope)
985 )
986 if value.name in scope and isinstance(scope[value.name], Annotation):
987 # re-assignment to name that was previously only an annotation
988 scope[value.name] = value
989 else:
990 # it may be a re-assignment to an already existing name
991 scope.setdefault(value.name, value)
992 else:
993 self.scope[value.name] = value
995 def _unknown_handler(self, node): # pragma: no cover
996 # this environment variable configures whether to error on unknown
997 # ast types.
998 #
999 # this is silent by default but the error is enabled for the pyflakes
1000 # testsuite.
1001 #
1002 # this allows new syntax to be added to python without *requiring*
1003 # changes from the pyflakes side. but will still produce an error
1004 # in the pyflakes testsuite (so more specific handling can be added if
1005 # needed).
1006 if os.environ.get('PYFLAKES_ERROR_UNKNOWN'):
1007 raise NotImplementedError(f'Unexpected type: {type(node)}')
1008 else:
1009 self.handleChildren(node)
1011 def getNodeHandler(self, node_class):
1012 try:
1013 return self._nodeHandlers[node_class]
1014 except KeyError:
1015 nodeType = node_class.__name__.upper()
1016 self._nodeHandlers[node_class] = handler = getattr(
1017 self, nodeType, self._unknown_handler,
1018 )
1019 return handler
1021 def handleNodeLoad(self, node, parent):
1022 name = getNodeName(node)
1023 if not name:
1024 return
1026 # only the following can access class scoped variables (since classes
1027 # aren't really a scope)
1028 # - direct accesses (not within a nested scope)
1029 # - generators
1030 # - type annotations (for generics, etc.)
1031 can_access_class_vars = None
1032 importStarred = None
1033 func_depth = 0
1035 # try enclosing function scopes and global scope
1036 for scope in reversed(self.scopeStack):
1037 if isinstance(scope, (FunctionScope, GeneratorScope)):
1038 func_depth += 1
1040 if isinstance(scope, ClassScope):
1041 if name == '__class__':
1042 return
1043 elif can_access_class_vars is False:
1044 # only generators used in a class scope can access the
1045 # names of the class. this is skipped during the first
1046 # iteration
1047 continue
1049 binding = scope.get(name, None)
1050 if isinstance(binding, Annotation) and not self._in_postponed_annotation:
1051 scope[name].used = (self.scope, node)
1052 continue
1054 elif name == 'print' and isinstance(binding, Builtin):
1055 if (isinstance(parent, ast.BinOp) and
1056 isinstance(parent.op, ast.RShift)):
1057 self.report(messages.InvalidPrintSyntax, node)
1058 elif (
1059 isinstance(binding, Importation) and
1060 binding.is_lazy and
1061 func_depth == 0 and
1062 not self._running_deferred
1063 ): # pragma: >=3.15 cover
1064 self.report(messages.EagerUseOfLazyImport, node, name, binding.source)
1066 try:
1067 scope[name].used = (self.scope, node)
1069 # if the name of SubImportation is same as
1070 # alias of other Importation and the alias
1071 # is used, SubImportation also should be marked as used.
1072 n = scope[name]
1073 if isinstance(n, Importation) and n._has_alias():
1074 try:
1075 scope[n.fullName].used = (self.scope, node)
1076 except KeyError:
1077 pass
1078 except KeyError:
1079 pass
1080 else:
1081 return
1083 importStarred = importStarred or scope.importStarred
1085 if can_access_class_vars is not False:
1086 can_access_class_vars = isinstance(
1087 scope, (TypeScope, ComprehensionScope),
1088 )
1090 if importStarred:
1091 from_list = []
1093 for scope in reversed(self.scopeStack):
1094 for binding in scope.values():
1095 if isinstance(binding, StarImportation):
1096 # mark '*' imports as used for each scope
1097 binding.used = (self.scope, node)
1098 from_list.append(binding.fullName)
1100 # report * usage, with a list of possible sources
1101 from_list = ', '.join(sorted(from_list))
1102 self.report(messages.ImportStarUsage, node, name, from_list)
1103 return
1105 if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
1106 # the special name __path__ is valid only in packages
1107 return
1109 if name in DetectClassScopedMagic.names and isinstance(self.scope, ClassScope):
1110 return
1112 # protected with a NameError handler?
1113 if 'NameError' not in self.exceptHandlers[-1]:
1114 self.report(messages.UndefinedName, node, name)
1116 def handleNodeStore(self, node):
1117 name = getNodeName(node)
1118 if not name:
1119 return
1120 # if the name hasn't already been defined in the current scope
1121 if isinstance(self.scope, FunctionScope) and name not in self.scope:
1122 # for each function or module scope above us
1123 for scope in self.scopeStack[:-1]:
1124 if not isinstance(scope, (FunctionScope, ModuleScope)):
1125 continue
1126 # if the name was defined in that scope, and the name has
1127 # been accessed already in the current scope, and hasn't
1128 # been declared global
1129 used = name in scope and scope[name].used
1130 if used and used[0] is self.scope:
1131 # then it's probably a mistake
1132 self.report(messages.UndefinedLocal,
1133 scope[name].used[1], name, scope[name].source)
1134 break
1136 parent_stmt = self.getParent(node)
1137 if isinstance(parent_stmt, ast.AnnAssign) and parent_stmt.value is None:
1138 binding = Annotation(name, node)
1139 elif isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
1140 parent_stmt != self._parents[node] and
1141 not self.isLiteralTupleUnpacking(parent_stmt)):
1142 binding = Binding(name, node)
1143 elif (
1144 name == '__all__' and
1145 isinstance(self.scope, ModuleScope) and
1146 isinstance(
1147 self._parents[node],
1148 (ast.Assign, ast.AugAssign, ast.AnnAssign)
1149 )
1150 ):
1151 binding = ExportBinding(name, self._parents[node], self.scope)
1152 elif isinstance(parent_stmt, ast.NamedExpr):
1153 binding = NamedExprAssignment(name, node)
1154 else:
1155 binding = Assignment(name, node)
1156 self.addBinding(node, binding)
1158 def handleNodeDelete(self, node):
1160 def on_conditional_branch():
1161 """
1162 Return `True` if node is part of a conditional body.
1163 """
1164 current = self._parents.get(node)
1165 while current:
1166 if isinstance(current, (ast.If, ast.While, ast.IfExp)):
1167 return True
1168 current = self._parents.get(current)
1169 return False
1171 if on_conditional_branch():
1172 # We cannot predict if this conditional branch is going to
1173 # be executed.
1174 return
1176 if isinstance(self.scope, (ClassScope, FunctionScope)):
1177 self.scope.indirect_assignments.pop(node.id, None)
1179 try:
1180 del self.scope[node.id]
1181 except KeyError:
1182 self.report(messages.UndefinedName, node, node.id)
1184 @contextlib.contextmanager
1185 def _enter_annotation(self, ann_type=AnnotationState.BARE):
1186 orig, self._in_annotation = self._in_annotation, ann_type
1187 try:
1188 yield
1189 finally:
1190 self._in_annotation = orig
1192 @property
1193 def _in_postponed_annotation(self):
1194 return (
1195 self._in_annotation == AnnotationState.STRING or
1196 (
1197 self._in_annotation == AnnotationState.BARE and
1198 (self.annotationsFutureEnabled or sys.version_info >= (3, 14))
1199 )
1200 )
1202 def handleChildren(self, tree, omit=None):
1203 for node in iter_child_nodes(tree, omit=omit):
1204 self.handleNode(node, tree)
1206 def isLiteralTupleUnpacking(self, node):
1207 if isinstance(node, ast.Assign):
1208 for child in node.targets + [node.value]:
1209 if not hasattr(child, 'elts'):
1210 return False
1211 return True
1213 def isDocstring(self, node):
1214 """
1215 Determine if the given node is a docstring, as long as it is at the
1216 correct place in the node tree.
1217 """
1218 return (
1219 isinstance(node, ast.Expr) and
1220 isinstance(node.value, ast.Constant) and
1221 isinstance(node.value.value, str)
1222 )
1224 def getDocstring(self, node):
1225 if (
1226 isinstance(node, ast.Expr) and
1227 isinstance(node.value, ast.Constant) and
1228 isinstance(node.value.value, str)
1229 ):
1230 return node.value.value, node.lineno - 1
1231 else:
1232 return None, None
1234 def handleNode(self, node, parent):
1235 if node is None:
1236 return
1237 if self.offset and getattr(node, 'lineno', None) is not None:
1238 node.lineno += self.offset[0]
1239 node.col_offset += self.offset[1]
1240 if (
1241 self.futuresAllowed and
1242 self.nodeDepth == 0 and
1243 not isinstance(node, ast.ImportFrom) and
1244 not self.isDocstring(node)
1245 ):
1246 self.futuresAllowed = False
1247 self.nodeDepth += 1
1248 self._node_depths[node] = self.nodeDepth
1249 self._parents[node] = parent
1250 try:
1251 handler = self.getNodeHandler(node.__class__)
1252 handler(node)
1253 finally:
1254 self.nodeDepth -= 1
1256 def handleDoctests(self, node):
1257 try:
1258 (docstring, node_lineno) = self.getDocstring(node.body[0])
1259 examples = docstring and _doctest_parser()(docstring)
1260 except (ValueError, IndexError):
1261 # e.g. line 6 of the docstring for <string> has inconsistent
1262 # leading whitespace: ...
1263 return
1264 if not examples:
1265 return
1267 # Place doctest in module scope
1268 saved_stack = self.scopeStack
1269 self.scopeStack = [self.scopeStack[0]]
1270 node_offset = self.offset or (0, 0)
1271 with self.in_scope(DoctestScope):
1272 if '_' not in self.scopeStack[0]:
1273 self.addBinding(None, Builtin('_'))
1274 for example in examples:
1275 try:
1276 tree = ast.parse(example.source, "<doctest>")
1277 except SyntaxError as e:
1278 position = (node_lineno + example.lineno + e.lineno,
1279 example.indent + 4 + (e.offset or 0))
1280 self.report(messages.DoctestSyntaxError, node, position)
1281 else:
1282 self.offset = (node_offset[0] + node_lineno + example.lineno,
1283 node_offset[1] + example.indent + 4)
1284 self.handleChildren(tree)
1285 self.offset = node_offset
1286 self.scopeStack = saved_stack
1288 @in_string_annotation
1289 def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset):
1290 try:
1291 tree = ast.parse(s)
1292 except SyntaxError:
1293 self.report(messages.ForwardAnnotationSyntaxError, node, s)
1294 return
1296 body = tree.body
1297 if len(body) != 1 or not isinstance(body[0], ast.Expr):
1298 self.report(messages.ForwardAnnotationSyntaxError, node, s)
1299 return
1301 parsed_annotation = tree.body[0].value
1302 for descendant in ast.walk(parsed_annotation):
1303 if (
1304 'lineno' in descendant._attributes and
1305 'col_offset' in descendant._attributes
1306 ):
1307 descendant.lineno = ref_lineno
1308 descendant.col_offset = ref_col_offset
1310 self.handleNode(parsed_annotation, node)
1312 def handle_annotation_always_deferred(self, annotation, parent):
1313 fn = in_annotation(Checker.handleNode)
1314 self.deferFunction(lambda: fn(self, annotation, parent))
1316 @in_annotation
1317 def handleAnnotation(self, annotation, node):
1318 if self.annotationsFutureEnabled or sys.version_info >= (3, 14):
1319 self.handle_annotation_always_deferred(annotation, node)
1320 else: # pragma: <3.14 cover
1321 self.handleNode(annotation, node)
1323 def ignore(self, node):
1324 pass
1326 # "stmt" type nodes
1327 DELETE = WHILE = WITH = WITHITEM = ASYNCWITH = EXPR = handleChildren
1329 PASS = ignore
1331 def FOR(self, node):
1332 self.handleNode(node.iter, node)
1333 self.handleChildren(node, omit=('iter',))
1335 ASYNCFOR = COMPREHENSION = FOR
1337 # "expr" type nodes
1338 BOOLOP = UNARYOP = SET = ATTRIBUTE = STARRED = NAMECONSTANT = \
1339 handleChildren
1341 def SUBSCRIPT(self, node):
1342 if _is_name_or_attr(node.value, 'Literal'):
1343 self.handleNode(node.value, node)
1344 with self._enter_annotation(AnnotationState.NONE):
1345 self.handleNode(node.slice, node)
1346 elif _is_name_or_attr(node.value, 'Annotated'):
1347 self.handleNode(node.value, node)
1349 if isinstance(node.slice, ast.Tuple):
1350 slice_tuple = node.slice
1351 else:
1352 slice_tuple = None
1354 # not a multi-arg `Annotated`
1355 if slice_tuple is None or len(slice_tuple.elts) < 2:
1356 self.handleNode(node.slice, node)
1357 else:
1358 # the first argument is the type
1359 self.handleNode(slice_tuple.elts[0], node)
1360 # the rest of the arguments are not
1361 with self._enter_annotation(AnnotationState.NONE):
1362 for arg in slice_tuple.elts[1:]:
1363 self.handleNode(arg, node)
1365 self.handleNode(node.ctx, node)
1366 else:
1367 if _is_any_typing_member(node.value, self.scopeStack):
1368 with self._enter_annotation():
1369 self.handleChildren(node)
1370 else:
1371 self.handleChildren(node)
1373 def _handle_string_dot_format(self, node):
1374 try:
1375 placeholders = tuple(parse_format_string(node.func.value.value))
1376 except ValueError as e:
1377 self.report(messages.StringDotFormatInvalidFormat, node, e)
1378 return
1380 auto = None
1381 next_auto = 0
1383 placeholder_positional = set()
1384 placeholder_named = set()
1386 def _add_key(fmtkey):
1387 """Returns True if there is an error which should early-exit"""
1388 nonlocal auto, next_auto
1390 if fmtkey is None: # end of string or `{` / `}` escapes
1391 return False
1393 # attributes / indices are allowed in `.format(...)`
1394 fmtkey, _, _ = fmtkey.partition('.')
1395 fmtkey, _, _ = fmtkey.partition('[')
1397 try:
1398 fmtkey = int(fmtkey)
1399 except ValueError:
1400 pass
1401 else: # fmtkey was an integer
1402 if auto is True:
1403 self.report(messages.StringDotFormatMixingAutomatic, node)
1404 return True
1405 else:
1406 auto = False
1408 if fmtkey == '':
1409 if auto is False:
1410 self.report(messages.StringDotFormatMixingAutomatic, node)
1411 return True
1412 else:
1413 auto = True
1415 fmtkey = next_auto
1416 next_auto += 1
1418 if isinstance(fmtkey, int):
1419 placeholder_positional.add(fmtkey)
1420 else:
1421 placeholder_named.add(fmtkey)
1423 return False
1425 for _, fmtkey, spec, _ in placeholders:
1426 if _add_key(fmtkey):
1427 return
1429 # spec can also contain format specifiers
1430 if spec is not None:
1431 try:
1432 spec_placeholders = tuple(parse_format_string(spec))
1433 except ValueError as e:
1434 self.report(messages.StringDotFormatInvalidFormat, node, e)
1435 return
1437 for _, spec_fmtkey, spec_spec, _ in spec_placeholders:
1438 # can't recurse again
1439 if spec_spec is not None and '{' in spec_spec:
1440 self.report(
1441 messages.StringDotFormatInvalidFormat,
1442 node,
1443 'Max string recursion exceeded',
1444 )
1445 return
1446 if _add_key(spec_fmtkey):
1447 return
1449 # bail early if there is *args or **kwargs
1450 if (
1451 # *args
1452 any(isinstance(arg, ast.Starred) for arg in node.args) or
1453 # **kwargs
1454 any(kwd.arg is None for kwd in node.keywords)
1455 ):
1456 return
1458 substitution_positional = set(range(len(node.args)))
1459 substitution_named = {kwd.arg for kwd in node.keywords}
1461 extra_positional = substitution_positional - placeholder_positional
1462 extra_named = substitution_named - placeholder_named
1464 missing_arguments = (
1465 (placeholder_positional | placeholder_named) -
1466 (substitution_positional | substitution_named)
1467 )
1469 if extra_positional:
1470 self.report(
1471 messages.StringDotFormatExtraPositionalArguments,
1472 node,
1473 ', '.join(sorted(str(x) for x in extra_positional)),
1474 )
1475 if extra_named:
1476 self.report(
1477 messages.StringDotFormatExtraNamedArguments,
1478 node,
1479 ', '.join(sorted(extra_named)),
1480 )
1481 if missing_arguments:
1482 self.report(
1483 messages.StringDotFormatMissingArgument,
1484 node,
1485 ', '.join(sorted(str(x) for x in missing_arguments)),
1486 )
1488 def CALL(self, node):
1489 if (
1490 isinstance(node.func, ast.Attribute) and
1491 isinstance(node.func.value, ast.Constant) and
1492 isinstance(node.func.value.value, str) and
1493 node.func.attr == 'format'
1494 ):
1495 self._handle_string_dot_format(node)
1497 def _annotation(n: ast.AST) -> None:
1498 with self._enter_annotation(AnnotationState.BARE):
1499 self.handleNode(n, node)
1501 def _annotations(nodes: list[ast.AST]) -> None:
1502 for n in nodes:
1503 _annotation(n)
1505 def _non_annotation(n: ast.AST) -> None:
1506 with self._enter_annotation(AnnotationState.NONE):
1507 self.handleNode(n, node)
1509 def _non_annotations(nodes: list[ast.AST]) -> None:
1510 for n in nodes:
1511 _non_annotation(n)
1513 if _is_typing(node.func, 'cast', self.scopeStack):
1514 _non_annotation(node.func)
1516 # cast("tp", val)
1517 _annotations(node.args[:1])
1518 _non_annotations(node.args[1:])
1520 # cast(typ="tp", val=val)
1521 for kwd in node.keywords:
1522 if kwd.arg == 'typ':
1523 _annotation(kwd)
1524 else:
1525 _non_annotation(kwd)
1527 elif _is_typing(node.func, 'assert_type', self.scopeStack):
1528 _non_annotation(node.func)
1530 # assert_type(val, "tp")
1531 _non_annotations(node.args[:1])
1532 _annotations(node.args[1:])
1533 _non_annotations(node.keywords)
1535 elif _is_typing(node.func, 'TypeVar', self.scopeStack):
1536 _non_annotation(node.func)
1537 _non_annotations(node.args[:1])
1539 # TypeVar("T", "int", "str")
1540 _annotations(node.args[1:])
1542 # TypeVar("T", bound="str")
1543 for kwd in node.keywords:
1544 if kwd.arg in ('bound', 'default'):
1545 _annotation(kwd)
1546 else:
1547 _non_annotation(kwd)
1549 elif (
1550 _is_typing(node.func, 'ParamSpec', self.scopeStack) or
1551 _is_typing(node.func, 'TypeVarTuple', self.scopeStack)
1552 ):
1553 _non_annotation(node.func)
1554 _non_annotations(node.args)
1556 # ParamSpec("P", default=..., bound=...)
1557 # TypeVarTuple("Ts", default=..., bound=...)
1558 for kwd in node.keywords:
1559 if kwd.arg in ('bound', 'default'):
1560 _annotation(kwd)
1561 else:
1562 _non_annotation(kwd)
1564 elif _is_typing(node.func, 'NewType', self.scopeStack):
1565 _non_annotation(node.func)
1566 _non_annotations(node.args[:1])
1568 # NewType("NT", "C")
1569 _annotations(node.args[1:])
1571 for kwd in node.keywords:
1572 if kwd.arg == 'tp':
1573 _annotation(kwd)
1574 else:
1575 _non_annotation(kwd)
1577 elif _is_typing(node.func, "TypedDict", self.scopeStack):
1578 _non_annotation(node.func)
1579 _non_annotations(node.args[:1])
1581 # TypedDict("a", {"a": int})
1582 if len(node.args) > 1 and isinstance(node.args[1], ast.Dict):
1583 for k, v in iter_dict_children(node.args[1]):
1584 _non_annotation(k)
1585 _annotation(v)
1586 _non_annotations(node.args[2:])
1587 else:
1588 _non_annotations(node.args[1:])
1590 # TypedDict("a", a=int)
1591 if sys.version_info >= (3, 13): # pragma: >=3.13 cover
1592 _non_annotations(node.keywords)
1593 else: # pragma: <3.13 cover
1594 _annotations(node.keywords)
1596 elif _is_typing(node.func, "NamedTuple", self.scopeStack):
1597 _non_annotation(node.func)
1598 _non_annotations(node.args[:1])
1600 # NamedTuple("a", [("a", int)])
1601 if (
1602 len(node.args) > 1 and
1603 isinstance(node.args[1], (ast.Tuple, ast.List))
1604 ):
1605 for elt in node.args[1].elts:
1606 if isinstance(elt, (ast.Tuple, ast.List)):
1607 _non_annotations(elt.elts[:1])
1608 _annotations(elt.elts[1:])
1609 else:
1610 _non_annotation(elt)
1611 _non_annotations(node.args[2:])
1612 else:
1613 _non_annotations(node.args[1:])
1615 # NamedTuple("a", a=int)
1616 if sys.version_info >= (3, 15): # pragma: >=3.15 cover
1617 _non_annotations(node.keywords)
1618 else: # pragma: <3.15 cover
1619 _annotations(node.keywords)
1620 else:
1621 self.handleChildren(node)
1623 def _handle_percent_format(self, node):
1624 try:
1625 placeholders = parse_percent_format(node.left.value)
1626 except ValueError:
1627 self.report(
1628 messages.PercentFormatInvalidFormat,
1629 node,
1630 'incomplete format',
1631 )
1632 return
1634 named = set()
1635 positional_count = 0
1636 positional = None
1637 for _, placeholder in placeholders:
1638 if placeholder is None:
1639 continue
1640 name, _, width, precision, conversion = placeholder
1642 if conversion == '%':
1643 continue
1645 if conversion not in VALID_CONVERSIONS:
1646 self.report(
1647 messages.PercentFormatUnsupportedFormatCharacter,
1648 node,
1649 conversion,
1650 )
1652 if positional is None and conversion:
1653 positional = name is None
1655 for part in (width, precision):
1656 if part is not None and '*' in part:
1657 if not positional:
1658 self.report(
1659 messages.PercentFormatStarRequiresSequence,
1660 node,
1661 )
1662 else:
1663 positional_count += 1
1665 if positional and name is not None:
1666 self.report(
1667 messages.PercentFormatMixedPositionalAndNamed,
1668 node,
1669 )
1670 return
1671 elif not positional and name is None:
1672 self.report(
1673 messages.PercentFormatMixedPositionalAndNamed,
1674 node,
1675 )
1676 return
1678 if positional:
1679 positional_count += 1
1680 else:
1681 named.add(name)
1683 if (
1684 isinstance(node.right, (ast.List, ast.Tuple)) and
1685 # does not have any *splats (py35+ feature)
1686 not any(
1687 isinstance(elt, ast.Starred)
1688 for elt in node.right.elts
1689 )
1690 ):
1691 substitution_count = len(node.right.elts)
1692 if positional and positional_count != substitution_count:
1693 self.report(
1694 messages.PercentFormatPositionalCountMismatch,
1695 node,
1696 positional_count,
1697 substitution_count,
1698 )
1699 elif not positional:
1700 self.report(messages.PercentFormatExpectedMapping, node)
1702 if (
1703 isinstance(node.right, ast.Dict) and
1704 all(
1705 isinstance(k, ast.Constant) and isinstance(k.value, str)
1706 for k in node.right.keys
1707 )
1708 ):
1709 if positional and positional_count > 1:
1710 self.report(messages.PercentFormatExpectedSequence, node)
1711 return
1713 substitution_keys = {k.value for k in node.right.keys}
1714 extra_keys = substitution_keys - named
1715 missing_keys = named - substitution_keys
1716 if not positional and extra_keys:
1717 self.report(
1718 messages.PercentFormatExtraNamedArguments,
1719 node,
1720 ', '.join(sorted(extra_keys)),
1721 )
1722 if not positional and missing_keys:
1723 self.report(
1724 messages.PercentFormatMissingArgument,
1725 node,
1726 ', '.join(sorted(missing_keys)),
1727 )
1729 def BINOP(self, node):
1730 if (
1731 isinstance(node.op, ast.Mod) and
1732 isinstance(node.left, ast.Constant) and
1733 isinstance(node.left.value, str)
1734 ):
1735 self._handle_percent_format(node)
1736 self.handleChildren(node)
1738 def CONSTANT(self, node):
1739 if isinstance(node.value, str) and self._in_annotation:
1740 fn = functools.partial(
1741 self.handleStringAnnotation,
1742 node.value,
1743 node,
1744 node.lineno,
1745 node.col_offset,
1746 )
1747 self.deferFunction(fn)
1749 # "slice" type nodes
1750 SLICE = EXTSLICE = INDEX = handleChildren
1752 # expression contexts are node instances too, though being constants
1753 LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
1755 # same for operators
1756 AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
1757 BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
1758 EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
1759 MATMULT = ignore
1761 def RAISE(self, node):
1762 self.handleChildren(node)
1764 arg = node.exc
1766 if isinstance(arg, ast.Call):
1767 if is_notimplemented_name_node(arg.func):
1768 # Handle "raise NotImplemented(...)"
1769 self.report(messages.RaiseNotImplemented, node)
1770 elif is_notimplemented_name_node(arg):
1771 # Handle "raise NotImplemented"
1772 self.report(messages.RaiseNotImplemented, node)
1774 # additional node types
1775 KEYWORD = FORMATTEDVALUE = handleChildren
1777 _in_fstring = False
1779 def JOINEDSTR(self, node):
1780 if (
1781 # the conversion / etc. flags are parsed as f-strings without
1782 # placeholders
1783 not self._in_fstring and
1784 not any(isinstance(x, ast.FormattedValue) for x in node.values)
1785 ):
1786 self.report(messages.FStringMissingPlaceholders, node)
1788 self._in_fstring, orig = True, self._in_fstring
1789 try:
1790 self.handleChildren(node)
1791 finally:
1792 self._in_fstring = orig
1794 def TEMPLATESTR(self, node): # pragma: >=3.14 cover
1795 if not any(isinstance(x, ast.Interpolation) for x in node.values):
1796 self.report(messages.TStringMissingPlaceholders, node)
1798 # similar to f-strings, conversion / etc. flags are parsed as f-strings
1799 # without placeholders
1800 self._in_fstring, orig = True, self._in_fstring
1801 try:
1802 self.handleChildren(node)
1803 finally:
1804 self._in_fstring = orig
1806 INTERPOLATION = handleChildren
1808 def DICT(self, node):
1809 # Complain if there are duplicate keys with different values
1810 # If they have the same value it's not going to cause potentially
1811 # unexpected behaviour so we'll not complain.
1812 keys = [
1813 convert_to_value(key) for key in node.keys
1814 ]
1816 key_counts = collections.Counter(keys)
1817 duplicate_keys = [
1818 key for key, count in key_counts.items()
1819 if count > 1
1820 ]
1822 for key in duplicate_keys:
1823 key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
1825 values = collections.Counter(
1826 convert_to_value(node.values[index])
1827 for index in key_indices
1828 )
1829 if any(count == 1 for value, count in values.items()):
1830 for key_index in key_indices:
1831 key_node = node.keys[key_index]
1832 if isinstance(key, VariableKey):
1833 self.report(messages.MultiValueRepeatedKeyVariable,
1834 key_node,
1835 key.name)
1836 else:
1837 self.report(
1838 messages.MultiValueRepeatedKeyLiteral,
1839 key_node,
1840 key,
1841 )
1843 for k, v in iter_dict_children(node):
1844 self.handleNode(k, node)
1845 self.handleNode(v, node)
1847 def IF(self, node):
1848 if isinstance(node.test, ast.Tuple) and node.test.elts != []:
1849 self.report(messages.IfTuple, node)
1850 self.handleChildren(node)
1852 IFEXP = IF
1854 def ASSERT(self, node):
1855 if isinstance(node.test, ast.Tuple) and node.test.elts != []:
1856 self.report(messages.AssertTuple, node)
1857 self.handleChildren(node)
1859 def GLOBAL(self, node):
1860 """
1861 Keep track of globals declarations.
1862 """
1863 global_scope_index = 1 if self._in_doctest() else 0
1864 global_scope = self.scopeStack[global_scope_index]
1866 # Ignore 'global' statement in global scope.
1867 if self.scope is not global_scope:
1869 # One 'global' statement can bind multiple (comma-delimited) names.
1870 for node_name in node.names:
1871 node_value = Assignment(node_name, node)
1873 # Remove UndefinedName messages already reported for this name.
1874 # TODO: if the global is not used in this scope, it does not
1875 # become a globally defined name. See test_unused_global.
1876 self.messages = [
1877 m for m in self.messages if not
1878 isinstance(m, messages.UndefinedName) or
1879 m.message_args[0] != node_name]
1881 # Bind name to global scope if it doesn't exist already.
1882 global_scope.setdefault(node_name, node_value)
1884 # Bind name to non-global scopes, but as already "used".
1885 node_value.used = (global_scope, node)
1886 for scope in self.scopeStack[global_scope_index + 1:]:
1887 scope[node_name] = node_value
1889 self.scope.indirect_assignments[node_name] = node
1891 NONLOCAL = GLOBAL
1893 def GENERATOREXP(self, node):
1894 # the first generator's iterable is eagerly executed in parent scope
1895 self.handleNode(node.generators[0].iter, node.generators[0])
1897 if isinstance(node, ast.GeneratorExp):
1898 scope_tp = GeneratorScope
1899 else:
1900 scope_tp = ComprehensionScope
1902 with self.in_scope(scope_tp):
1903 self.handleChildren(node.generators[0], omit=('iter',))
1904 for gen in node.generators[1:]:
1905 self.handleNode(gen, node)
1906 self.handleChildren(node, omit=('generators',))
1908 LISTCOMP = DICTCOMP = SETCOMP = GENERATOREXP
1910 def NAME(self, node):
1911 """
1912 Handle occurrence of Name (which can be a load/store/delete access.)
1913 """
1914 # Locate the name in locals / function / globals scopes.
1915 if isinstance(node.ctx, ast.Load):
1916 self.handleNodeLoad(node, self.getParent(node))
1917 if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
1918 isinstance(self._parents[node], ast.Call)):
1919 # we are doing locals() call in current scope
1920 self.scope.usesLocals = True
1921 elif isinstance(node.ctx, ast.Store):
1922 self.handleNodeStore(node)
1923 elif isinstance(node.ctx, ast.Del):
1924 self.handleNodeDelete(node)
1925 else:
1926 # Unknown context
1927 raise RuntimeError(f"Got impossible expression context: {node.ctx!r}")
1929 def CONTINUE(self, node):
1930 # Walk the tree up until we see a loop (OK), a function or class
1931 # definition (not OK), for 'continue', a finally block (not OK), or
1932 # the top module scope (not OK)
1933 n = node
1934 while n in self._parents:
1935 n, n_child = self._parents[n], n
1936 if isinstance(n, (ast.While, ast.For, ast.AsyncFor)):
1937 # Doesn't apply unless it's in the loop itself
1938 if n_child not in n.orelse:
1939 return
1940 if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
1941 break
1942 if isinstance(node, ast.Continue):
1943 self.report(messages.ContinueOutsideLoop, node)
1944 else: # ast.Break
1945 self.report(messages.BreakOutsideLoop, node)
1947 BREAK = CONTINUE
1949 def RETURN(self, node):
1950 if isinstance(self.scope, (ClassScope, ModuleScope)):
1951 self.report(messages.ReturnOutsideFunction, node)
1952 return
1954 self.handleNode(node.value, node)
1956 def YIELD(self, node):
1957 if isinstance(self.scope, (ClassScope, ModuleScope)):
1958 self.report(messages.YieldOutsideFunction, node)
1959 return
1961 self.handleNode(node.value, node)
1963 AWAIT = YIELDFROM = YIELD
1965 def FUNCTIONDEF(self, node):
1966 for deco in node.decorator_list:
1967 self.handleNode(deco, node)
1969 with self._type_param_scope(node):
1970 self.LAMBDA(node)
1972 self.addBinding(node, FunctionDefinition(node.name, node))
1973 # doctest does not process doctest within a doctest,
1974 # or in nested functions.
1975 if (self.withDoctest and
1976 not self._in_doctest() and
1977 not isinstance(self.scope, FunctionScope)):
1978 self.deferFunction(lambda: self.handleDoctests(node))
1980 ASYNCFUNCTIONDEF = FUNCTIONDEF
1982 def LAMBDA(self, node):
1983 args = []
1984 annotations = []
1986 for arglist in (
1987 node.args.posonlyargs,
1988 node.args.args,
1989 node.args.kwonlyargs,
1990 ):
1991 for arg in arglist:
1992 args.append(arg.arg)
1993 annotations.append(arg.annotation)
1994 defaults = node.args.defaults + node.args.kw_defaults
1996 for wildcard in (node.args.vararg, node.args.kwarg):
1997 if not wildcard:
1998 continue
1999 args.append(wildcard.arg)
2000 annotations.append(wildcard.annotation)
2002 if not isinstance(node, ast.Lambda):
2003 annotations.append(node.returns)
2005 if len(set(args)) < len(args):
2006 for (idx, arg) in enumerate(args):
2007 if arg in args[:idx]:
2008 self.report(messages.DuplicateArgument, node, arg)
2010 for annotation in annotations:
2011 self.handleAnnotation(annotation, node)
2013 for default in defaults:
2014 self.handleNode(default, node)
2016 def runFunction():
2017 with self.in_scope(FunctionScope):
2018 self.handleChildren(
2019 node,
2020 omit=('decorator_list', 'returns', 'type_params'),
2021 )
2023 self.deferFunction(runFunction)
2025 def ARGUMENTS(self, node):
2026 self.handleChildren(node, omit=('defaults', 'kw_defaults'))
2028 def ARG(self, node):
2029 self.addBinding(node, Argument(node.arg, node))
2031 def CLASSDEF(self, node):
2032 """
2033 Check names used in a class definition, including its decorators, base
2034 classes, and the body of its definition. Additionally, add its name to
2035 the current scope.
2036 """
2037 for deco in node.decorator_list:
2038 self.handleNode(deco, node)
2040 with self._type_param_scope(node):
2041 for baseNode in node.bases:
2042 self.handleNode(baseNode, node)
2043 for keywordNode in node.keywords:
2044 self.handleNode(keywordNode, node)
2045 with self.in_scope(ClassScope):
2046 # doctest does not process doctest within a doctest
2047 # classes within classes are processed.
2048 if (self.withDoctest and
2049 not self._in_doctest() and
2050 not isinstance(self.scope, FunctionScope)):
2051 self.deferFunction(lambda: self.handleDoctests(node))
2052 for stmt in node.body:
2053 self.handleNode(stmt, node)
2055 self.addBinding(node, ClassDefinition(node.name, node))
2057 def ASSIGN(self, node):
2058 self.handleNode(node.value, node)
2059 self.handleChildren(node, omit=('value',))
2061 NAMEDEXPR = ASSIGN
2063 def AUGASSIGN(self, node):
2064 self.handleNodeLoad(node.target, node)
2065 self.handleNode(node.value, node)
2066 self.handleNode(node.target, node)
2068 def ANNASSIGN(self, node):
2069 self.handleAnnotation(node.annotation, node)
2070 # If the assignment has value, handle the *value* now.
2071 if node.value:
2072 # If the annotation is `TypeAlias`, handle the *value* as an annotation.
2073 if _is_typing(node.annotation, 'TypeAlias', self.scopeStack):
2074 with self._enter_annotation(AnnotationState.BARE):
2075 self.handleNode(node.value, node)
2076 else:
2077 self.handleNode(node.value, node)
2078 self.handleNode(node.target, node)
2080 def TYPEALIAS(self, node): # pragma: >=3.12 cover
2081 with self._type_param_scope(node):
2082 self.handle_annotation_always_deferred(node.value, node)
2083 self.handleNode(node.name, node)
2085 def TUPLE(self, node):
2086 if isinstance(node.ctx, ast.Store):
2087 # Python 3 advanced tuple unpacking: a, *b, c = d.
2088 # Only one starred expression is allowed, and no more than 1<<8
2089 # assignments are allowed before a stared expression. There is
2090 # also a limit of 1<<24 expressions after the starred expression,
2091 # which is impossible to test due to memory restrictions, but we
2092 # add it here anyway
2093 has_starred = False
2094 star_loc = -1
2095 for i, n in enumerate(node.elts):
2096 if isinstance(n, ast.Starred):
2097 if has_starred:
2098 self.report(messages.TwoStarredExpressions, node)
2099 # The SyntaxError doesn't distinguish two from more
2100 # than two.
2101 break
2102 has_starred = True
2103 star_loc = i
2104 if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
2105 self.report(messages.TooManyExpressionsInStarredAssignment, node)
2106 self.handleChildren(node)
2108 LIST = TUPLE
2110 def _in_try(self, node): # pragma: >=3.15 cover
2111 while True:
2112 node = self.getParent(node)
2113 if isinstance(node, (ast.Try, ast.TryStar, ast.ExceptHandler)):
2114 return True
2115 elif isinstance(node, ast.Module):
2116 return False
2118 def IMPORT(self, node):
2119 lazy = sys.version_info >= (3, 15) and node.is_lazy
2120 if lazy and not isinstance(self.scope, ModuleScope): # pragma: >=3.15 cover
2121 self.report(messages.LazyImportNotAtModuleScope, node)
2122 return
2123 elif lazy and self._in_try(node): # pragma: >=3.15 cover
2124 self.report(messages.LazyImportNotAtModuleScope, node)
2125 return
2127 for alias in node.names:
2128 if '.' in alias.name and not alias.asname:
2129 importation = SubmoduleImportation(
2130 alias.name, node,
2131 is_lazy=lazy,
2132 )
2133 else:
2134 name = alias.asname or alias.name
2135 importation = Importation(name, node, alias.name, is_lazy=lazy)
2136 self.addBinding(node, importation)
2138 def IMPORTFROM(self, node):
2139 if node.module == '__future__':
2140 if not self.futuresAllowed:
2141 self.report(messages.LateFutureImport, node)
2142 else:
2143 self.futuresAllowed = False
2145 lazy = sys.version_info >= (3, 15) and node.is_lazy
2146 if lazy and not isinstance(self.scope, ModuleScope): # pragma: >=3.15 cover
2147 self.report(messages.LazyImportNotAtModuleScope, node)
2148 return
2149 elif lazy and self._in_try(node): # pragma: >=3.15 cover
2150 self.report(messages.LazyImportNotAtModuleScope, node)
2151 return
2153 module = ('.' * node.level) + (node.module or '')
2155 for alias in node.names:
2156 name = alias.asname or alias.name
2157 if node.module == '__future__':
2158 importation = FutureImportation(name, node, self.scope)
2159 if alias.name not in __future__.all_feature_names: # pragma: <3.14 cover
2160 self.report(messages.FutureFeatureNotDefined,
2161 node, alias.name)
2162 if alias.name == 'annotations':
2163 self.annotationsFutureEnabled = True
2164 elif alias.name == '*':
2165 if not isinstance(self.scope, ModuleScope):
2166 self.report(messages.ImportStarNotPermitted, node, module)
2167 continue
2168 elif lazy: # pragma: >=3.15 cover
2169 self.report(messages.LazyImportStarNotPermitted, node, module)
2170 continue
2172 self.scope.importStarred = True
2173 self.report(messages.ImportStarUsed, node, module)
2174 importation = StarImportation(module, node)
2175 else:
2176 importation = ImportationFrom(
2177 name, node, module, alias.name,
2178 is_lazy=lazy,
2179 )
2180 self.addBinding(node, importation)
2182 def TRY(self, node):
2183 handler_names = []
2184 # List the exception handlers
2185 for i, handler in enumerate(node.handlers):
2186 if isinstance(handler.type, ast.Tuple):
2187 for exc_type in handler.type.elts:
2188 handler_names.append(getNodeName(exc_type))
2189 elif handler.type:
2190 handler_names.append(getNodeName(handler.type))
2192 if handler.type is None and i < len(node.handlers) - 1:
2193 self.report(messages.DefaultExceptNotLast, handler)
2194 # Memorize the except handlers and process the body
2195 self.exceptHandlers.append(handler_names)
2196 for child in node.body:
2197 self.handleNode(child, node)
2198 self.exceptHandlers.pop()
2199 # Process the other nodes: "except:", "else:", "finally:"
2200 self.handleChildren(node, omit='body')
2202 TRYSTAR = TRY
2204 def EXCEPTHANDLER(self, node):
2205 if node.name is None:
2206 self.handleChildren(node)
2207 return
2209 # If the name already exists in the scope, modify state of existing
2210 # binding.
2211 if node.name in self.scope:
2212 self.handleNodeStore(node)
2214 # 3.x: the name of the exception, which is not a Name node, but a
2215 # simple string, creates a local that is only bound within the scope of
2216 # the except: block. As such, temporarily remove the existing binding
2217 # to more accurately determine if the name is used in the except:
2218 # block.
2220 try:
2221 prev_definition = self.scope.pop(node.name)
2222 except KeyError:
2223 prev_definition = None
2225 self.handleNodeStore(node)
2226 self.handleChildren(node)
2228 # See discussion on https://github.com/PyCQA/pyflakes/pull/59
2230 # We're removing the local name since it's being unbound after leaving
2231 # the except: block and it's always unbound if the except: block is
2232 # never entered. This will cause an "undefined name" error raised if
2233 # the checked code tries to use the name afterwards.
2234 #
2235 # Unless it's been removed already. Then do nothing.
2237 try:
2238 binding = self.scope.pop(node.name)
2239 except KeyError:
2240 pass
2241 else:
2242 if not binding.used:
2243 self.report(messages.UnusedVariable, node, node.name)
2245 # Restore.
2246 if prev_definition:
2247 self.scope[node.name] = prev_definition
2249 def COMPARE(self, node):
2250 left = node.left
2251 for op, right in zip(node.ops, node.comparators):
2252 if (
2253 isinstance(op, (ast.Is, ast.IsNot)) and (
2254 _is_const_non_singleton(left) or
2255 _is_const_non_singleton(right)
2256 )
2257 ):
2258 self.report(messages.IsLiteral, node)
2259 left = right
2261 self.handleChildren(node)
2263 MATCH = MATCH_CASE = MATCHCLASS = MATCHOR = MATCHSEQUENCE = handleChildren
2264 MATCHSINGLETON = MATCHVALUE = handleChildren
2266 def _match_target(self, node):
2267 self.handleNodeStore(node)
2268 self.handleChildren(node)
2270 MATCHAS = MATCHMAPPING = MATCHSTAR = _match_target
2272 @contextlib.contextmanager
2273 def _type_param_scope(self, node):
2274 with contextlib.ExitStack() as ctx:
2275 if sys.version_info >= (3, 12): # pragma: >=3.12 cover
2276 ctx.enter_context(self.in_scope(TypeScope))
2277 for param in node.type_params:
2278 self.handleNode(param, node)
2279 yield
2281 def TYPEVAR(self, node): # pragma: >=3.12 cover
2282 self.handleNodeStore(node)
2283 self.handle_annotation_always_deferred(node.bound, node)
2285 PARAMSPEC = TYPEVARTUPLE = handleNodeStore