fname
stringlengths
63
176
rel_fname
stringclasses
706 values
line
int64
-1
4.5k
name
stringlengths
1
81
kind
stringclasses
2 values
category
stringclasses
2 values
info
stringlengths
0
77.9k
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
603
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
629
visit_functiondef
def
function
def visit_functiondef(self, node: nodes.FunctionDef) -> None: if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # If it is the first non import instruction of the module, record it. if self._first_non_import_node: return # Check if the node belongs to an `If` or a `Try` block. If they # contain imports, skip recording this node. if not isinstance(node.parent.scope(), nodes.Module): return root = node while not isinstance(root.parent, nodes.Module): root = root.parent if isinstance(root, (nodes.If, nodes.TryFinally, nodes.TryExcept)): if any(root.nodes_of_class((nodes.Import, nodes.ImportFrom))): return self._first_non_import_node = node visit_classdef = visit_for = visit_while = visit_functiondef def _check_misplaced_future(self, node): basename = node.modname if basename == "__future__": # check if this is the first non-docstring statement in the module prev = node.previous_sibling() if prev: # consecutive future statements are possible if not ( isinstance(prev, nodes.ImportFrom) and prev.modname == "__future__" ): self.add_message("misplaced-future", node=node) return def _check_same_line_imports(self, node): # Detect duplicate imports on the same line. names = (name for name, _ in node.names) counter = collections.Counter(names) for name, count in counter.items(): if count > 1: self.add_message("reimported", node=node, args=(name, node.fromlineno)) def _check_position(self, node): """Check `node` import or importfrom node position is correct. Send a message if `node` comes before another instruction """ # if a first non-import instruction has already been encountered, # it means the import comes after it and therefore is not well placed if self._first_non_import_node: self.add_message("wrong-import-position", node=node, args=node.as_string()) def _record_import(self, node, importedmodnode): """Record the package `node` imports from.""" if isinstance(node, nodes.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: importedname = node.names[0][0].split(".")[0] if isinstance(node, nodes.ImportFrom) and (node.level or 0) >= 1: # We need the importedname with first point to detect local package # Example of node: # 'from .my_package1 import MyClass1' # the output should be '.my_package1' instead of 'my_package1' # Example of node: # 'from . import my_package2' # the output should be '.my_package2' instead of '{pyfile}' importedname = "." + importedname self._imports_stack.append((node, importedname)) @staticmethod def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
630
is_message_enabled
ref
function
if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
638
scope
ref
function
if not isinstance(node.parent.scope(), nodes.Module):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
646
nodes_of_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
653
_check_misplaced_future
def
function
def _check_misplaced_future(self, node): basename = node.modname if basename == "__future__": # check if this is the first non-docstring statement in the module prev = node.previous_sibling() if prev: # consecutive future statements are possible if not ( isinstance(prev, nodes.ImportFrom) and prev.modname == "__future__" ): self.add_message("misplaced-future", node=node) return def _check_same_line_imports(self, node): # Detect duplicate imports on the same line. names = (name for name, _ in node.names) counter = collections.Counter(names) for name, count in counter.items(): if count > 1: self.add_message("reimported", node=node, args=(name, node.fromlineno)) def _check_position(self, node): """Check `node` import or importfrom node position is correct. Send a message if `node` comes before another instruction """ # if a first non-import instruction has already been encountered, # it means the import comes after it and therefore is not well placed if self._first_non_import_node: self.add_message("wrong-import-position", node=node, args=node.as_string()) def _record_import(self, node, importedmodnode): """Record the package `node` imports from.""" if isinstance(node, nodes.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: importedname = node.names[0][0].split(".")[0] if isinstance(node, nodes.ImportFrom) and (node.level or 0) >= 1: # We need the importedname with first point to detect local package # Example of node: # 'from .my_package1 import MyClass1' # the output should be '.my_package1' instead of 'my_package1' # Example of node: # 'from . import my_package2' # the output should be '.my_package2' instead of '{pyfile}' importedname = "." + importedname self._imports_stack.append((node, importedname)) @staticmethod def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
657
previous_sibling
ref
function
prev = node.previous_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
663
add_message
ref
function
self.add_message("misplaced-future", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
666
_check_same_line_imports
def
function
def _check_same_line_imports(self, node): # Detect duplicate imports on the same line. names = (name for name, _ in node.names) counter = collections.Counter(names) for name, count in counter.items(): if count > 1: self.add_message("reimported", node=node, args=(name, node.fromlineno)) def _check_position(self, node): """Check `node` import or importfrom node position is correct. Send a message if `node` comes before another instruction """ # if a first non-import instruction has already been encountered, # it means the import comes after it and therefore is not well placed if self._first_non_import_node: self.add_message("wrong-import-position", node=node, args=node.as_string()) def _record_import(self, node, importedmodnode): """Record the package `node` imports from.""" if isinstance(node, nodes.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: importedname = node.names[0][0].split(".")[0] if isinstance(node, nodes.ImportFrom) and (node.level or 0) >= 1: # We need the importedname with first point to detect local package # Example of node: # 'from .my_package1 import MyClass1' # the output should be '.my_package1' instead of 'my_package1' # Example of node: # 'from . import my_package2' # the output should be '.my_package2' instead of '{pyfile}' importedname = "." + importedname self._imports_stack.append((node, importedname)) @staticmethod def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
672
add_message
ref
function
self.add_message("reimported", node=node, args=(name, node.fromlineno))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
674
_check_position
def
function
def _check_position(self, node): """Check `node` import or importfrom node position is correct. Send a message if `node` comes before another instruction """ # if a first non-import instruction has already been encountered, # it means the import comes after it and therefore is not well placed if self._first_non_import_node: self.add_message("wrong-import-position", node=node, args=node.as_string()) def _record_import(self, node, importedmodnode): """Record the package `node` imports from.""" if isinstance(node, nodes.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: importedname = node.names[0][0].split(".")[0] if isinstance(node, nodes.ImportFrom) and (node.level or 0) >= 1: # We need the importedname with first point to detect local package # Example of node: # 'from .my_package1 import MyClass1' # the output should be '.my_package1' instead of 'my_package1' # Example of node: # 'from . import my_package2' # the output should be '.my_package2' instead of '{pyfile}' importedname = "." + importedname self._imports_stack.append((node, importedname)) @staticmethod def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
682
add_message
ref
function
self.add_message("wrong-import-position", node=node, args=node.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
682
as_string
ref
function
self.add_message("wrong-import-position", node=node, args=node.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
684
_record_import
def
function
def _record_import(self, node, importedmodnode): """Record the package `node` imports from.""" if isinstance(node, nodes.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: importedname = node.names[0][0].split(".")[0] if isinstance(node, nodes.ImportFrom) and (node.level or 0) >= 1: # We need the importedname with first point to detect local package # Example of node: # 'from .my_package1 import MyClass1' # the output should be '.my_package1' instead of 'my_package1' # Example of node: # 'from . import my_package2' # the output should be '.my_package2' instead of '{pyfile}' importedname = "." + importedname self._imports_stack.append((node, importedname)) @staticmethod def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
706
_is_fallback_import
def
function
def _is_fallback_import(node, imports): imports = [import_node for (import_node, _) in imports] return any(astroid.are_exclusive(import_node, node) for import_node in imports) def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
708
are_exclusive
ref
function
return any(astroid.are_exclusive(import_node, node) for import_node in imports)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
710
_check_imports_order
def
function
def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category. Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds third or first party ordered import external_imports = [] local_imports = [] third_party_not_ignored = [] first_party_not_ignored = [] local_not_ignored = [] isort_driver = IsortDriver(self.config) for node, modname in self._imports_stack: if modname.startswith("."): package = "." + modname.split(".")[1] else: package = modname.split(".")[0] nested = not isinstance(node.parent, nodes.Module) ignore_for_import_order = not self.linter.is_message_enabled( "wrong-import-order", node.fromlineno ) import_category = isort_driver.place_module(package) node_and_package_import = (node, package) if import_category in {"FUTURE", "STDLIB"}: std_imports.append(node_and_package_import) wrong_import = ( third_party_not_ignored or first_party_not_ignored or local_not_ignored ) if self._is_fallback_import(node, wrong_import): continue if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'standard import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "THIRDPARTY": third_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: third_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = first_party_not_ignored or local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'third party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "FIRSTPARTY": first_party_imports.append(node_and_package_import) external_imports.append(node_and_package_import) if not nested: if not ignore_for_import_order: first_party_not_ignored.append(node_and_package_import) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) wrong_import = local_not_ignored if wrong_import and not nested: self.add_message( "wrong-import-order", node=node, args=( f'first party import "{node.as_string()}"', f'"{wrong_import[0][0].as_string()}"', ), ) elif import_category == "LOCALFOLDER": local_imports.append((node, package)) if not nested: if not ignore_for_import_order: local_not_ignored.append((node, package)) else: self.linter.add_ignored_message( "wrong-import-order", node.fromlineno, node ) return std_imports, external_imports, local_imports def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
724
IsortDriver
ref
function
isort_driver = IsortDriver(self.config)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
731
is_message_enabled
ref
function
ignore_for_import_order = not self.linter.is_message_enabled(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
734
place_module
ref
function
import_category = isort_driver.place_module(package)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
743
_is_fallback_import
ref
function
if self._is_fallback_import(node, wrong_import):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
746
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
750
as_string
ref
function
f'standard import "{node.as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
751
as_string
ref
function
f'"{wrong_import[0][0].as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
761
add_ignored_message
ref
function
self.linter.add_ignored_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
766
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
770
as_string
ref
function
f'third party import "{node.as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
771
as_string
ref
function
f'"{wrong_import[0][0].as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
781
add_ignored_message
ref
function
self.linter.add_ignored_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
786
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
790
as_string
ref
function
f'first party import "{node.as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
791
as_string
ref
function
f'"{wrong_import[0][0].as_string()}"',
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
800
add_ignored_message
ref
function
self.linter.add_ignored_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
805
_get_imported_module
def
function
def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) except astroid.TooManyLevelsError: if _ignore_import_failure(importnode, modname, self._ignored_modules): return None self.add_message("relative-beyond-top-level", node=importnode) except astroid.AstroidSyntaxError as exc: message = f"Cannot import {modname!r} due to syntax error {str(exc.error)!r}" # pylint: disable=no-member; false positive self.add_message("syntax-error", line=importnode.lineno, args=message) except astroid.AstroidBuildingException: if not self.linter.is_message_enabled("import-error"): return None if _ignore_import_failure(importnode, modname, self._ignored_modules): return None if not self.config.analyse_fallback_blocks and is_from_fallback_block( importnode ): return None dotted_modname = get_import_name(importnode, modname) self.add_message("import-error", args=repr(dotted_modname), node=importnode) return None def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
807
do_import_module
ref
function
return importnode.do_import_module(modname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
809
_ignore_import_failure
ref
function
if _ignore_import_failure(importnode, modname, self._ignored_modules):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
811
add_message
ref
function
self.add_message("relative-beyond-top-level", node=importnode)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
814
add_message
ref
function
self.add_message("syntax-error", line=importnode.lineno, args=message)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
817
is_message_enabled
ref
function
if not self.linter.is_message_enabled("import-error"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
819
_ignore_import_failure
ref
function
if _ignore_import_failure(importnode, modname, self._ignored_modules):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
821
is_from_fallback_block
ref
function
if not self.config.analyse_fallback_blocks and is_from_fallback_block(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
826
get_import_name
ref
function
dotted_modname = get_import_name(importnode, modname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
827
add_message
ref
function
self.add_message("import-error", args=repr(dotted_modname), node=importnode)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
830
_add_imported_module
def
function
def _add_imported_module( self, node: Union[nodes.Import, nodes.ImportFrom], importedmodname: str ) -> None: """Notify an imported module, used to analyze dependencies.""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroid.modutils.get_module_part( importedmodname, module_file ) except ImportError: pass in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard( node.parent ) if context_name == importedmodname: self.add_message("import-self", node=node) elif not astroid.modutils.is_standard_module(importedmodname): # if this is not a package __init__ module if base != "__init__" and context_name not in self._module_pkg: # record the module's parent, or the module itself if this is # a top level module, as the package it belongs to self._module_pkg[context_name] = context_name.rsplit(".", 1)[0] # handle dependencies dependencies_stat: Dict[str, Union[Set]] = self.linter.stats.dependencies importedmodnames = dependencies_stat.setdefault(importedmodname, set()) if context_name not in importedmodnames: importedmodnames.add(context_name) # update import graph self.import_graph[context_name].add(importedmodname) if ( not self.linter.is_message_enabled("cyclic-import", line=node.lineno) or in_type_checking_block ): self._excluded_edges[context_name].add(importedmodname) def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
834
root
ref
function
module_file = node.root().file
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
835
root
ref
function
context_name = node.root().name
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
836
splitext
ref
function
base = os.path.splitext(os.path.basename(module_file))[0]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
836
basename
ref
function
base = os.path.splitext(os.path.basename(module_file))[0]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
839
get_module_part
ref
function
importedmodname = astroid.modutils.get_module_part(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
845
is_typing_guard
ref
function
in_type_checking_block = isinstance(node.parent, nodes.If) and is_typing_guard(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
850
add_message
ref
function
self.add_message("import-self", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
852
is_standard_module
ref
function
elif not astroid.modutils.is_standard_module(importedmodname):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
868
is_message_enabled
ref
function
not self.linter.is_message_enabled("cyclic-import", line=node.lineno)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
873
_check_preferred_module
def
function
def _check_preferred_module(self, node, mod_path): """Check if the module has a preferred replacement.""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ) def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
876
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
882
_check_import_as_rename
def
function
def _check_import_as_rename( self, node: Union[nodes.Import, nodes.ImportFrom] ) -> None: names = node.names for name in names: if not all(name): return splitted_packages = name[0].rsplit(".", maxsplit=1) import_name = splitted_packages[-1] aliased_name = name[1] if import_name != aliased_name: continue if len(splitted_packages) == 1: self.add_message("useless-import-alias", node=node) elif len(splitted_packages) == 2: self.add_message( "consider-using-from-import", node=node, args=(splitted_packages[0], import_name), ) def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
897
add_message
ref
function
self.add_message("useless-import-alias", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
899
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
905
_check_reimport
def
function
def _check_reimport(self, node, basename=None, level=None): """Check if the import is necessary (i.e. not already done).""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame(future=_True) root = node.root() contexts = [(frame, level)] if root is not frame: contexts.append((root, None)) for known_context, known_level in contexts: for name, alias in node.names: first = _get_first_import( node, known_context, name, basename, known_level, alias ) if first is not None: self.add_message( "reimported", node=node, args=(name, first.fromlineno) ) def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
907
is_message_enabled
ref
function
if not self.linter.is_message_enabled("reimported"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
910
frame
ref
function
frame = node.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
911
root
ref
function
root = node.root()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
918
_get_first_import
ref
function
first = _get_first_import(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
922
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
926
_report_external_dependencies
def
function
def _report_external_dependencies(self, sect, _, _dummy): """Return a verbatim layout for displaying dependencies.""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str)) def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
928
_make_tree_defs
ref
function
dep_info = _make_tree_defs(self._external_dependencies_info().items())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
928
_external_dependencies_info
ref
function
dep_info = _make_tree_defs(self._external_dependencies_info().items())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
930
EmptyReportError
ref
function
raise EmptyReportError()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
931
_repr_tree_defs
ref
function
tree_str = _repr_tree_defs(dep_info)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
932
VerbatimText
ref
function
sect.append(VerbatimText(tree_str))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
934
_report_dependencies_graph
def
function
def _report_dependencies_graph(self, sect, _, _dummy): """Write dependencies as a dot (graphviz) file.""" dep_info = self.linter.stats.dependencies if not dep_info or not ( self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph ): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, "") filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, "external ") filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, "internal ") def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
942
EmptyReportError
ref
function
raise EmptyReportError()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
945
_make_graph
ref
function
_make_graph(filename, dep_info, sect, "")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
948
_make_graph
ref
function
_make_graph(filename, self._external_dependencies_info(), sect, "external ")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
948
_external_dependencies_info
ref
function
_make_graph(filename, self._external_dependencies_info(), sect, "external ")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
951
_make_graph
ref
function
_make_graph(filename, self._internal_dependencies_info(), sect, "internal ")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
951
_internal_dependencies_info
ref
function
_make_graph(filename, self._internal_dependencies_info(), sect, "internal ")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
953
_filter_dependencies_graph
def
function
def _filter_dependencies_graph(self, internal): """Build the internal or the external dependency graph.""" graph = collections.defaultdict(set) for importee, importers in self.linter.stats.dependencies.items(): for importer in importers: package = self._module_pkg.get(importer, importer) is_inside = importee.startswith(package) if is_inside and internal or not is_inside and not internal: graph[importee].add(importer) return graph @astroid.decorators.cached def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
965
_external_dependencies_info
def
function
def _external_dependencies_info(self): """Return cached external dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_False) @astroid.decorators.cached def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
969
_filter_dependencies_graph
ref
function
return self._filter_dependencies_graph(internal=False)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
972
_internal_dependencies_info
def
function
def _internal_dependencies_info(self): """Return cached internal dependencies information or build and cache them """ return self._filter_dependencies_graph(internal=_True) def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
976
_filter_dependencies_graph
ref
function
return self._filter_dependencies_graph(internal=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
978
_check_wildcard_imports
def
function
def _check_wildcard_imports(self, node, imported_module): if node.root().package: # Skip the check if in __init__.py issue #2026 return wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module) for name, _ in node.names: if name == "*" and not wildcard_import_is_allowed: self.add_message("wildcard-import", args=node.modname, node=node) def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
979
root
ref
function
if node.root().package:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
983
_wildcard_import_is_allowed
ref
function
wildcard_import_is_allowed = self._wildcard_import_is_allowed(imported_module)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
986
add_message
ref
function
self.add_message("wildcard-import", args=node.modname, node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
988
_wildcard_import_is_allowed
def
function
def _wildcard_import_is_allowed(self, imported_module): return ( self.config.allow_wildcard_with_all and imported_module is not None and "__all__" in imported_module.locals ) def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
995
_check_toplevel
def
function
def _check_toplevel(self, node): """Check whether the import is made outside the module toplevel.""" # If the scope of the import is a module, then obviously it is # not outside the module toplevel. if isinstance(node.scope(), nodes.Module): return module_names = [ f"{node.modname}.{name[0]}" if isinstance(node, nodes.ImportFrom) else name[0] for name in node.names ] # Get the full names of all the imports that are only allowed at the module level scoped_imports = [ name for name in module_names if name not in self._allow_any_import_level ] if scoped_imports: self.add_message( "import-outside-toplevel", args=", ".join(scoped_imports), node=node )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
999
scope
ref
function
if isinstance(node.scope(), nodes.Module):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
1,015
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
1,020
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(ImportsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
1,021
register_checker
ref
function
linter.register_checker(ImportsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
1,021
ImportsChecker
ref
function
linter.register_checker(ImportsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
116
is_method_call
def
function
def is_method_call(func, types=(), methods=()): """Determines if a BoundMethod node represents a method call. Args: func (astroid.BoundMethod): The BoundMethod AST node to check. types (Optional[String]): Optional sequence of caller type names to restrict check. methods (Optional[String]): Optional sequence of method names to restrict check. Returns: bool: true if the node represents a method call for the given type and method names, _False otherwise. """ return ( isinstance(func, astroid.BoundMethod) and isinstance(func.bound, astroid.Instance) and (func.bound.name in types if types else _True) and (func.name in methods if methods else _True) )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
136
LoggingChecker
def
class
visit_module visit_importfrom visit_import visit_call _check_log_method _helper_string _is_operand_literal_str _check_call_func _check_format_string
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
167
visit_module
def
function
def visit_module(self, _: nodes.Module) -> None: """Clears any state left in this checker from last module checked.""" # The code being checked can just as easily "import logging as foo", # so it is necessary to process the imports and store in this field # what name the logging module is actually given. self._logging_names: Set[str] = set() logging_mods = self.config.logging_modules self._format_style = self.config.logging_format_style self._logging_modules = set(logging_mods) self._from_imports = {} for logging_mod in logging_mods: parts = logging_mod.rsplit(".", 1) if len(parts) > 1: self._from_imports[parts[0]] = parts[1] def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Checks to see if a module uses a non-Python logging module.""" try: logging_name = self._from_imports[node.modname] for module, as_name in node.names: if module == logging_name: self._logging_names.add(as_name or module) except KeyError: pass def visit_import(self, node: nodes.Import) -> None: """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module) @check_messages(*MSGS) def visit_call(self, node: nodes.Call) -> None: """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, nodes.Attribute) and isinstance(node.func.expr, nodes.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): for inferred in infer_all(node.func): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, nodes.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return _True, inferred._proxied.name return _False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name) def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], nodes.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message( "logging-not-lazy", node=node, args=(self._helper_string(node),), ) elif isinstance(node.args[format_pos], nodes.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], nodes.Const): self._check_format_string(node, format_pos) elif isinstance(node.args[format_pos], nodes.JoinedStr): self.add_message( "logging-fstring-interpolation", node=node, args=(self._helper_string(node),), ) def _helper_string(self, node): """Create a string that lists the valid types of formatting for this node.""" valid_types = ["lazy %"] if not self.linter.is_message_enabled( "logging-fstring-formatting", node.fromlineno ): valid_types.append("fstring") if not self.linter.is_message_enabled( "logging-format-interpolation", node.fromlineno ): valid_types.append(".format()") if not self.linter.is_message_enabled("logging-not-lazy", node.fromlineno): valid_types.append("%") return " or ".join(valid_types) @staticmethod def _is_operand_literal_str(operand): """Return _True if the operand in argument is a literal string.""" return isinstance(operand, nodes.Const) and operand.name == "str" def _check_call_func(self, node: nodes.Call): """Checks that function call is not format_string.format().""" func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if ( isinstance(func, astroid.BoundMethod) and is_method_call(func, types, methods) and not is_complex_format_str(func.bound) ): self.add_message( "logging-format-interpolation", node=node, args=(self._helper_string(node),), ) def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (nodes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value required_num_args = 0 if isinstance(format_string, bytes): format_string = format_string.decode() if isinstance(format_string, str): try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": ( keyword_arguments, implicit_pos_args, explicit_pos_args, ) = utils.parse_format_method_string(format_string) keyword_args_cnt = len( {k for k, l in keyword_arguments if not isinstance(k, int)} ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
184
visit_importfrom
def
function
def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Checks to see if a module uses a non-Python logging module.""" try: logging_name = self._from_imports[node.modname] for module, as_name in node.names: if module == logging_name: self._logging_names.add(as_name or module) except KeyError: pass def visit_import(self, node: nodes.Import) -> None: """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module) @check_messages(*MSGS) def visit_call(self, node: nodes.Call) -> None: """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, nodes.Attribute) and isinstance(node.func.expr, nodes.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): for inferred in infer_all(node.func): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, nodes.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return _True, inferred._proxied.name return _False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name) def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], nodes.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message( "logging-not-lazy", node=node, args=(self._helper_string(node),), ) elif isinstance(node.args[format_pos], nodes.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], nodes.Const): self._check_format_string(node, format_pos) elif isinstance(node.args[format_pos], nodes.JoinedStr): self.add_message( "logging-fstring-interpolation", node=node, args=(self._helper_string(node),), ) def _helper_string(self, node): """Create a string that lists the valid types of formatting for this node.""" valid_types = ["lazy %"] if not self.linter.is_message_enabled( "logging-fstring-formatting", node.fromlineno ): valid_types.append("fstring") if not self.linter.is_message_enabled( "logging-format-interpolation", node.fromlineno ): valid_types.append(".format()") if not self.linter.is_message_enabled("logging-not-lazy", node.fromlineno): valid_types.append("%") return " or ".join(valid_types) @staticmethod def _is_operand_literal_str(operand): """Return _True if the operand in argument is a literal string.""" return isinstance(operand, nodes.Const) and operand.name == "str" def _check_call_func(self, node: nodes.Call): """Checks that function call is not format_string.format().""" func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if ( isinstance(func, astroid.BoundMethod) and is_method_call(func, types, methods) and not is_complex_format_str(func.bound) ): self.add_message( "logging-format-interpolation", node=node, args=(self._helper_string(node),), ) def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (nodes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value required_num_args = 0 if isinstance(format_string, bytes): format_string = format_string.decode() if isinstance(format_string, str): try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": ( keyword_arguments, implicit_pos_args, explicit_pos_args, ) = utils.parse_format_method_string(format_string) keyword_args_cnt = len( {k for k, l in keyword_arguments if not isinstance(k, int)} ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
194
visit_import
def
function
def visit_import(self, node: nodes.Import) -> None: """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module) @check_messages(*MSGS) def visit_call(self, node: nodes.Call) -> None: """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, nodes.Attribute) and isinstance(node.func.expr, nodes.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): for inferred in infer_all(node.func): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, nodes.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return _True, inferred._proxied.name return _False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name) def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], nodes.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message( "logging-not-lazy", node=node, args=(self._helper_string(node),), ) elif isinstance(node.args[format_pos], nodes.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], nodes.Const): self._check_format_string(node, format_pos) elif isinstance(node.args[format_pos], nodes.JoinedStr): self.add_message( "logging-fstring-interpolation", node=node, args=(self._helper_string(node),), ) def _helper_string(self, node): """Create a string that lists the valid types of formatting for this node.""" valid_types = ["lazy %"] if not self.linter.is_message_enabled( "logging-fstring-formatting", node.fromlineno ): valid_types.append("fstring") if not self.linter.is_message_enabled( "logging-format-interpolation", node.fromlineno ): valid_types.append(".format()") if not self.linter.is_message_enabled("logging-not-lazy", node.fromlineno): valid_types.append("%") return " or ".join(valid_types) @staticmethod def _is_operand_literal_str(operand): """Return _True if the operand in argument is a literal string.""" return isinstance(operand, nodes.Const) and operand.name == "str" def _check_call_func(self, node: nodes.Call): """Checks that function call is not format_string.format().""" func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if ( isinstance(func, astroid.BoundMethod) and is_method_call(func, types, methods) and not is_complex_format_str(func.bound) ): self.add_message( "logging-format-interpolation", node=node, args=(self._helper_string(node),), ) def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (nodes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value required_num_args = 0 if isinstance(format_string, bytes): format_string = format_string.decode() if isinstance(format_string, str): try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": ( keyword_arguments, implicit_pos_args, explicit_pos_args, ) = utils.parse_format_method_string(format_string) keyword_args_cnt = len( {k for k, l in keyword_arguments if not isinstance(k, int)} ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
200
check_messages
ref
function
@check_messages(*MSGS)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/logging.py
pylint/checkers/logging.py
201
visit_call
def
function
def visit_call(self, node: nodes.Call) -> None: """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, nodes.Attribute) and isinstance(node.func.expr, nodes.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): for inferred in infer_all(node.func): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, nodes.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return _True, inferred._proxied.name return _False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name) def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], nodes.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message( "logging-not-lazy", node=node, args=(self._helper_string(node),), ) elif isinstance(node.args[format_pos], nodes.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], nodes.Const): self._check_format_string(node, format_pos) elif isinstance(node.args[format_pos], nodes.JoinedStr): self.add_message( "logging-fstring-interpolation", node=node, args=(self._helper_string(node),), ) def _helper_string(self, node): """Create a string that lists the valid types of formatting for this node.""" valid_types = ["lazy %"] if not self.linter.is_message_enabled( "logging-fstring-formatting", node.fromlineno ): valid_types.append("fstring") if not self.linter.is_message_enabled( "logging-format-interpolation", node.fromlineno ): valid_types.append(".format()") if not self.linter.is_message_enabled("logging-not-lazy", node.fromlineno): valid_types.append("%") return " or ".join(valid_types) @staticmethod def _is_operand_literal_str(operand): """Return _True if the operand in argument is a literal string.""" return isinstance(operand, nodes.Const) and operand.name == "str" def _check_call_func(self, node: nodes.Call): """Checks that function call is not format_string.format().""" func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if ( isinstance(func, astroid.BoundMethod) and is_method_call(func, types, methods) and not is_complex_format_str(func.bound) ): self.add_message( "logging-format-interpolation", node=node, args=(self._helper_string(node),), ) def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (nodes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value required_num_args = 0 if isinstance(format_string, bytes): format_string = format_string.decode() if isinstance(format_string, str): try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": ( keyword_arguments, implicit_pos_args, explicit_pos_args, ) = utils.parse_format_method_string(format_string) keyword_args_cnt = len( {k for k, l in keyword_arguments if not isinstance(k, int)} ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)