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/format.py
pylint/checkers/format.py
678
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
682
check_line_length
def
function
def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
687
search
ref
function
if len(line) > max_chars and not ignore_long_line.search(line):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
689
add_ignored_message
ref
function
self.linter.add_ignored_message("line-too-long", i)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
691
add_message
ref
function
self.add_message("line-too-long", line=i, args=(len(line), max_chars))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
694
remove_pylint_option_from_lines
def
function
def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
698
start
ref
function
lines[: options_pattern_obj.start(1)].rstrip()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
699
end
ref
function
+ lines[options_pattern_obj.end(1) :]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
704
is_line_length_check_activated
def
function
def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
707
parse_pragma
ref
function
for pragma in parse_pragma(pylint_pattern_match_object.group(2)):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
716
specific_splitlines
def
function
def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
740
check_lines
def
function
def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
756
specific_splitlines
ref
function
split_lines = self.specific_splitlines(lines)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
759
check_line_ending
ref
function
self.check_line_ending(line, lineno + offset)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
777
search
ref
function
mobj = OPTION_PO.search(lines)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
780
is_line_length_check_activated
ref
function
if not self.is_line_length_check_activated(mobj):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
783
remove_pylint_option_from_lines
ref
function
lines = self.remove_pylint_option_from_lines(mobj)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
786
specific_splitlines
ref
function
for offset, line in enumerate(self.specific_splitlines(lines)):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
787
check_line_length
ref
function
self.check_line_length(line, lineno + offset, checker_off)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
789
check_indent_level
def
function
def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
807
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
814
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(FormatChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
815
register_checker
ref
function
linter.register_checker(FormatChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
815
FormatChecker
ref
function
linter.register_checker(FormatChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
78
_qualified_names
def
function
def _qualified_names(modname): """Split the names of the given module into subparts. For example, _qualified_names('pylint.checkers.ImportsChecker') returns ['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker'] """ names = modname.split(".") return [".".join(names[0 : i + 1]) for i in range(len(names))]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
90
_get_first_import
def
function
def _get_first_import(node, context, name, base, level, alias): """Return the node where [base.]<name> is imported or None if not found.""" fullname = f"{base}.{name}" if base else name first = None found = _False for first in context.body: if first is node: continue if first.scope() is node.scope() and first.fromlineno > node.fromlineno: continue if isinstance(first, nodes.Import): if any(fullname == iname[0] for iname in first.names): found = _True break elif isinstance(first, nodes.ImportFrom): if level == first.level: for imported_name, imported_alias in first.names: if fullname == f"{first.modname}.{imported_name}": found = _True break if ( name != "*" and name == imported_name and not (alias or imported_alias) ): found = _True break if found: break if found and not astroid.are_exclusive(first, node): return first return None
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
99
scope
ref
function
if first.scope() is node.scope() and first.fromlineno > node.fromlineno:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
99
scope
ref
function
if first.scope() is node.scope() and first.fromlineno > node.fromlineno:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
120
are_exclusive
ref
function
if found and not astroid.are_exclusive(first, node):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
125
_ignore_import_failure
def
function
def _ignore_import_failure(node, modname, ignored_modules): for submodule in _qualified_names(modname): if submodule in ignored_modules: return _True if is_node_in_guarded_import_block(node): # Ignore import failure if part of guarded import block # I.e. `sys.version_info` or `typing.TYPE_CHECKING` return _True return node_ignores_exception(node, ImportError)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
126
_qualified_names
ref
function
for submodule in _qualified_names(modname):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
130
is_node_in_guarded_import_block
ref
function
if is_node_in_guarded_import_block(node):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
135
node_ignores_exception
ref
function
return node_ignores_exception(node, ImportError)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
141
_make_tree_defs
def
function
def _make_tree_defs(mod_files_list): """Get a list of 2-uple (module, list_of_files_which_import_this_module), it will return a dictionary to represent this as a tree """ tree_defs = {} for mod, files in mod_files_list: node = (tree_defs, ()) for prefix in mod.split("."): node = node[0].setdefault(prefix, [{}, []]) node[1] += files return tree_defs
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
154
_repr_tree_defs
def
function
def _repr_tree_defs(data, indent_str=None): """Return a string which represents imports as a tree.""" lines = [] nodes_items = data.items() for i, (mod, (sub, files)) in enumerate(sorted(nodes_items, key=lambda x: x[0])): files = "" if not files else f"({','.join(sorted(files))})" if indent_str is None: lines.append(f"{mod} {files}") sub_indent_str = " " else: lines.append(rf"{indent_str}\-{mod} {files}") if i == len(nodes_items) - 1: sub_indent_str = f"{indent_str} " else: sub_indent_str = f"{indent_str}| " if sub: lines.append(_repr_tree_defs(sub, sub_indent_str)) return "\n".join(lines)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
170
_repr_tree_defs
ref
function
lines.append(_repr_tree_defs(sub, sub_indent_str))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
174
_dependencies_graph
def
function
def _dependencies_graph(filename: str, dep_info: Dict[str, Set[str]]) -> str: """Write dependencies as a dot (graphviz) file.""" done = {} printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR") printer.emit('URL="." node[shape="box"]') for modname, dependencies in sorted(dep_info.items()): sorted_dependencies = sorted(dependencies) done[modname] = 1 printer.emit_node(modname) for depmodname in sorted_dependencies: if depmodname not in done: done[depmodname] = 1 printer.emit_node(depmodname) for depmodname, dependencies in sorted(dep_info.items()): for modname in sorted(dependencies): printer.emit_edge(modname, depmodname) return printer.generate(filename)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
177
DotBackend
ref
function
printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
177
splitext
ref
function
printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
177
basename
ref
function
printer = DotBackend(os.path.splitext(os.path.basename(filename))[0], rankdir="LR")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
178
emit
ref
function
printer.emit('URL="." node[shape="box"]')
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
182
emit_node
ref
function
printer.emit_node(modname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
186
emit_node
ref
function
printer.emit_node(depmodname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
189
emit_edge
ref
function
printer.emit_edge(modname, depmodname)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
190
generate
ref
function
return printer.generate(filename)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
193
_make_graph
def
function
def _make_graph( filename: str, dep_info: Dict[str, Set[str]], sect: Section, gtype: str
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
199
_dependencies_graph
ref
function
outputfile = _dependencies_graph(filename, dep_info)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
200
Paragraph
ref
function
sect.append(Paragraph((f"{gtype}imports graph has been written to {outputfile}",)))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
303
ImportsChecker
def
class
__init__ _compute_site_packages open _import_graph_without_ignored_edges close deprecated_modules visit_import visit_importfrom leave_module compute_first_non_import_node visit_functiondef _check_misplaced_future _check_same_line_imports _check_position _record_import _is_fallback_import _check_imports_order _get_imported_module _add_imported_module _check_preferred_module _check_import_as_rename _check_reimport _report_external_dependencies _report_dependencies_graph _filter_dependencies_graph _external_dependencies_info _internal_dependencies_info _check_wildcard_imports _wildcard_import_is_allowed _check_toplevel
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
443
_compute_site_packages
ref
function
self._site_packages = self._compute_site_packages()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
446
_compute_site_packages
def
function
def _compute_site_packages(): def _normalized_path(path): return os.path.normcase(os.path.abspath(path)) paths = set() real_prefix = getattr(sys, "real_prefix", None) for prefix in filter(None, (real_prefix, sys.prefix)): path = sysconfig.get_python_lib(prefix=prefix) path = _normalized_path(path) paths.add(path) # Handle Debian's derivatives /usr/local. if os.path.isfile("/etc/debian_version"): for prefix in filter(None, (real_prefix, sys.prefix)): libpython = os.path.join( prefix, "local", "lib", "python" + sysconfig.get_python_version(), "dist-packages", ) paths.add(libpython) return paths def open(self): """Called before visiting project (i.e set of modules).""" self.linter.stats.dependencies = {} self.linter.stats = self.linter.stats self.import_graph = collections.defaultdict(set) self._module_pkg = {} # mapping of modules to the pkg they belong in self._excluded_edges = collections.defaultdict(set) self._ignored_modules = get_global_option(self, "ignored-modules", default=[]) # Build a mapping {'module': 'preferred-module'} self.preferred_modules = dict( module.split(":") for module in self.config.preferred_modules if ":" in module ) self._allow_any_import_level = set(self.config.allow_any_import_level) def _import_graph_without_ignored_edges(self): filtered_graph = copy.deepcopy(self.import_graph) for node in filtered_graph: filtered_graph[node].difference_update(self._excluded_edges[node]) return filtered_graph def close(self): """Called before visiting project (i.e set of modules).""" if self.linter.is_message_enabled("cyclic-import"): graph = self._import_graph_without_ignored_edges() vertices = list(graph) for cycle in get_cycles(graph, vertices=vertices): self.add_message("cyclic-import", args=" -> ".join(cycle)) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self.config.deprecated_modules @check_messages(*MSGS) def visit_import(self, node: nodes.Import) -> None: """Triggered when an import statement is seen.""" self._check_reimport(node) self._check_import_as_rename(node) self._check_toplevel(node) names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports", args=", ".join(names), node=node) for name in names: self.check_deprecated_module(node, name) self._check_preferred_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: continue self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
447
_normalized_path
def
function
def _normalized_path(path): return os.path.normcase(os.path.abspath(path)) paths = set() real_prefix = getattr(sys, "real_prefix", None) for prefix in filter(None, (real_prefix, sys.prefix)): path = sysconfig.get_python_lib(prefix=prefix) path = _normalized_path(path) paths.add(path) # Handle Debian's derivatives /usr/local. if os.path.isfile("/etc/debian_version"): for prefix in filter(None, (real_prefix, sys.prefix)): libpython = os.path.join( prefix, "local", "lib", "python" + sysconfig.get_python_version(), "dist-packages", ) paths.add(libpython) return paths def open(self): """Called before visiting project (i.e set of modules).""" self.linter.stats.dependencies = {} self.linter.stats = self.linter.stats self.import_graph = collections.defaultdict(set) self._module_pkg = {} # mapping of modules to the pkg they belong in self._excluded_edges = collections.defaultdict(set) self._ignored_modules = get_global_option(self, "ignored-modules", default=[]) # Build a mapping {'module': 'preferred-module'} self.preferred_modules = dict( module.split(":") for module in self.config.preferred_modules if ":" in module ) self._allow_any_import_level = set(self.config.allow_any_import_level) def _import_graph_without_ignored_edges(self): filtered_graph = copy.deepcopy(self.import_graph) for node in filtered_graph: filtered_graph[node].difference_update(self._excluded_edges[node]) return filtered_graph def close(self): """Called before visiting project (i.e set of modules).""" if self.linter.is_message_enabled("cyclic-import"): graph = self._import_graph_without_ignored_edges() vertices = list(graph) for cycle in get_cycles(graph, vertices=vertices): self.add_message("cyclic-import", args=" -> ".join(cycle)) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self.config.deprecated_modules @check_messages(*MSGS) def visit_import(self, node: nodes.Import) -> None: """Triggered when an import statement is seen.""" self._check_reimport(node) self._check_import_as_rename(node) self._check_toplevel(node) names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports", args=", ".join(names), node=node) for name in names: self.check_deprecated_module(node, name) self._check_preferred_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: continue self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
448
normcase
ref
function
return os.path.normcase(os.path.abspath(path))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
448
abspath
ref
function
return os.path.normcase(os.path.abspath(path))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
454
_normalized_path
ref
function
path = _normalized_path(path)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
458
isfile
ref
function
if os.path.isfile("/etc/debian_version"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
477
get_global_option
ref
function
self._ignored_modules = get_global_option(self, "ignored-modules", default=[])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
486
_import_graph_without_ignored_edges
def
function
def _import_graph_without_ignored_edges(self): filtered_graph = copy.deepcopy(self.import_graph) for node in filtered_graph: filtered_graph[node].difference_update(self._excluded_edges[node]) return filtered_graph def close(self): """Called before visiting project (i.e set of modules).""" if self.linter.is_message_enabled("cyclic-import"): graph = self._import_graph_without_ignored_edges() vertices = list(graph) for cycle in get_cycles(graph, vertices=vertices): self.add_message("cyclic-import", args=" -> ".join(cycle)) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self.config.deprecated_modules @check_messages(*MSGS) def visit_import(self, node: nodes.Import) -> None: """Triggered when an import statement is seen.""" self._check_reimport(node) self._check_import_as_rename(node) self._check_toplevel(node) names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports", args=", ".join(names), node=node) for name in names: self.check_deprecated_module(node, name) self._check_preferred_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: continue self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
494
is_message_enabled
ref
function
if self.linter.is_message_enabled("cyclic-import"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
495
_import_graph_without_ignored_edges
ref
function
graph = self._import_graph_without_ignored_edges()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
497
get_cycles
ref
function
for cycle in get_cycles(graph, vertices=vertices):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
498
add_message
ref
function
self.add_message("cyclic-import", args=" -> ".join(cycle))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
500
deprecated_modules
def
function
def deprecated_modules(self): """Callback returning the deprecated modules.""" return self.config.deprecated_modules @check_messages(*MSGS) def visit_import(self, node: nodes.Import) -> None: """Triggered when an import statement is seen.""" self._check_reimport(node) self._check_import_as_rename(node) self._check_toplevel(node) names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports", args=", ".join(names), node=node) for name in names: self.check_deprecated_module(node, name) self._check_preferred_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: continue self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
504
check_messages
ref
function
@check_messages(*MSGS)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
505
visit_import
def
function
def visit_import(self, node: nodes.Import) -> None: """Triggered when an import statement is seen.""" self._check_reimport(node) self._check_import_as_rename(node) self._check_toplevel(node) names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports", args=", ".join(names), node=node) for name in names: self.check_deprecated_module(node, name) self._check_preferred_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: continue self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
507
_check_reimport
ref
function
self._check_reimport(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
508
_check_import_as_rename
ref
function
self._check_import_as_rename(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
509
_check_toplevel
ref
function
self._check_toplevel(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
513
add_message
ref
function
self.add_message("multiple-imports", args=", ".join(names), node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
516
check_deprecated_module
ref
function
self.check_deprecated_module(node, name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
517
_check_preferred_module
ref
function
self._check_preferred_module(node, name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
518
_get_imported_module
ref
function
imported_module = self._get_imported_module(node, name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
521
_check_position
ref
function
self._check_position(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
522
scope
ref
function
if isinstance(node.scope(), nodes.Module):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
523
_record_import
ref
function
self._record_import(node, imported_module)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
528
_add_imported_module
ref
function
self._add_imported_module(node, imported_module.name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
530
check_messages
ref
function
@check_messages(*MSGS)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
531
visit_importfrom
def
function
def visit_importfrom(self, node: nodes.ImportFrom) -> None: """Triggered when a from statement is seen.""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self.check_deprecated_module(node, basename) self._check_preferred_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) self._check_toplevel(node) if isinstance(node.parent, nodes.Module): # Allow imports nested self._check_position(node) if isinstance(node.scope(), nodes.Module): self._record_import(node, imported_module) if imported_module is None: return for name, _ in node.names: if name != "*": self._add_imported_module(node, f"{imported_module.name}.{name}") else: self._add_imported_module(node, imported_module.name) @check_messages(*MSGS) def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
534
_get_imported_module
ref
function
imported_module = self._get_imported_module(node, basename)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
536
_check_import_as_rename
ref
function
self._check_import_as_rename(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
537
_check_misplaced_future
ref
function
self._check_misplaced_future(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
538
check_deprecated_module
ref
function
self.check_deprecated_module(node, basename)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
539
_check_preferred_module
ref
function
self._check_preferred_module(node, basename)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
540
_check_wildcard_imports
ref
function
self._check_wildcard_imports(node, imported_module)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
541
_check_same_line_imports
ref
function
self._check_same_line_imports(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
542
_check_reimport
ref
function
self._check_reimport(node, basename=basename, level=node.level)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
543
_check_toplevel
ref
function
self._check_toplevel(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
547
_check_position
ref
function
self._check_position(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
548
scope
ref
function
if isinstance(node.scope(), nodes.Module):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
549
_record_import
ref
function
self._record_import(node, imported_module)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
554
_add_imported_module
ref
function
self._add_imported_module(node, f"{imported_module.name}.{name}")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
556
_add_imported_module
ref
function
self._add_imported_module(node, imported_module.name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
558
check_messages
ref
function
@check_messages(*MSGS)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
559
leave_module
def
function
def leave_module(self, node: nodes.Module) -> None: # Check imports are grouped by category (standard, 3rd party, local) std_imports, ext_imports, loc_imports = self._check_imports_order(node) # Check that imports are grouped by package within a given category met_import: Set[str] = set() # set for 'import x' style met_from: Set[str] = set() # set for 'from x import y' style current_package = None for import_node, import_name in std_imports + ext_imports + loc_imports: if not self.linter.is_message_enabled( "ungrouped-imports", import_node.fromlineno ): continue met = met_from if isinstance(import_node, nodes.ImportFrom) else met_import package, _, _ = import_name.partition(".") if ( current_package and current_package != package and package in met and is_node_in_guarded_import_block(import_node) is _False ): self.add_message("ungrouped-imports", node=import_node, args=package) current_package = package met.add(package) self._imports_stack = [] self._first_non_import_node = None def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
561
_check_imports_order
ref
function
std_imports, ext_imports, loc_imports = self._check_imports_order(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
568
is_message_enabled
ref
function
if not self.linter.is_message_enabled(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
578
is_node_in_guarded_import_block
ref
function
and is_node_in_guarded_import_block(import_node) is False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
580
add_message
ref
function
self.add_message("ungrouped-imports", node=import_node, args=package)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/imports.py
pylint/checkers/imports.py
587
compute_first_non_import_node
def
function
def compute_first_non_import_node(self, node): if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno): return # if the node does not contain an import instruction, and if it is the # first node of the module, keep a track of it (all the import positions # of the module will be compared to the position of this first # instruction) if self._first_non_import_node: return if not isinstance(node.parent, nodes.Module): return nested_allowed = [nodes.TryExcept, nodes.TryFinally] is_nested_allowed = [ allowed for allowed in nested_allowed if isinstance(node, allowed) ] if is_nested_allowed and any( node.nodes_of_class((nodes.Import, nodes.ImportFrom)) ): return if isinstance(node, nodes.Assign): # Add compatibility for module level dunder names # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names valid_targets = [ isinstance(target, nodes.AssignName) and target.name.startswith("__") and target.name.endswith("__") for target in node.targets ] if all(valid_targets): return self._first_non_import_node = node visit_tryfinally = ( visit_tryexcept ) = ( visit_assignattr ) = ( visit_assign ) = ( visit_ifexp ) = visit_comprehension = visit_expr = visit_if = compute_first_non_import_node 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
588
is_message_enabled
ref
function
if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno):