imported = {}<EOL>for filename in listdir(directory):<EOL><INDENT>base, extension = splitext(filename)<EOL>if base in imported or base == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if (<EOL>extension in PY_EXTS<EOL>and base != "<STR_LIT>"<EOL>or (not extension and isdir(join(directory, base)))<EOL>):<EOL><INDENT>try:<EOL><INDENT>module = modutils.load_module_from_file(join(directory, filename))<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>except ImportError as exc:<EOL><INDENT>print(<EOL>"<STR_LIT>" % (filename, exc), file=sys.stderr<EOL>)<EOL><DEDENT>else:<EOL><INDENT>if hasattr(module, "<STR_LIT>"):<EOL><INDENT>module.register(linter)<EOL>imported[base] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>

load all module and package in the given directory, looking for a
    'register' function in each one, used to register pylint checkers


def get_global_option(checker, option, default=None):

<EOL>try:<EOL><INDENT>return getattr(checker.config, option.replace("<STR_LIT:->", "<STR_LIT:_>"))<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for provider in checker.linter.options_providers:<EOL><INDENT>for options in provider.options:<EOL><INDENT>if options[<NUM_LIT:0>] == option:<EOL><INDENT>return getattr(provider.config, option.replace("<STR_LIT:->", "<STR_LIT:_>"))<EOL><DEDENT><DEDENT><DEDENT>return default<EOL>

Retrieve an option defined by the given *checker* or
    by all known option providers.

    It will look in the list of all options providers
    until the given *option* will be found.
    If the option wasn't found, the *default* value will be returned.


return [word.strip() for word in string.split(sep) if word.strip()]<EOL>

return a list of stripped string by splitting the string given as
    argument on `sep` (',' by default). Empty string are discarded.

    >>> _splitstrip('a, b, c   ,  4,,')
    ['a', 'b', 'c', '4']
    >>> _splitstrip('a')
    ['a']
    >>> _splitstrip('a,\nb,\nc,')
    ['a', 'b', 'c']

    :type string: str or unicode
    :param string: a csv line

    :type sep: str or unicode
    :param sep: field separator, default to the comma (',')

    :rtype: str or unicode
    :return: the unquoted string (or the input string if it wasn't quoted)


if not string:<EOL><INDENT>return string<EOL><DEDENT>if string[<NUM_LIT:0>] in "<STR_LIT>":<EOL><INDENT>string = string[<NUM_LIT:1>:]<EOL><DEDENT>if string[-<NUM_LIT:1>] in "<STR_LIT>":<EOL><INDENT>string = string[:-<NUM_LIT:1>]<EOL><DEDENT>return string<EOL>

remove optional quotes (simple or double) from the string

    :type string: str or unicode
    :param string: an optionally quoted string

    :rtype: str or unicode
    :return: the unquoted string (or the input string if it wasn't quoted)


lines = [line.strip() for line in string.splitlines()]<EOL>return "<STR_LIT>" + ("<STR_LIT>" % linesep).join(lines)<EOL>


if isinstance(value, (list, tuple)):<EOL><INDENT>value = "<STR_LIT:U+002C>".join(_format_option_value(optdict, item) for item in value)<EOL><DEDENT>elif isinstance(value, dict):<EOL><INDENT>value = "<STR_LIT:U+002C>".join("<STR_LIT>" % (k, v) for k, v in value.items())<EOL><DEDENT>elif hasattr(value, "<STR_LIT>"):  <EOL><INDENT>value = value.pattern<EOL><DEDENT>elif optdict.get("<STR_LIT:type>") == "<STR_LIT>":<EOL><INDENT>value = "<STR_LIT:yes>" if value else "<STR_LIT>"<EOL><DEDENT>elif isinstance(value, str) and value.isspace():<EOL><INDENT>value = "<STR_LIT>" % value<EOL><DEDENT>return value<EOL>

return the user input's value from a 'compiled' value


def format_section(stream, section, options, doc=None):

if doc:<EOL><INDENT>print(_comment(doc), file=stream)<EOL><DEDENT>print("<STR_LIT>" % section, file=stream)<EOL>_ini_format(stream, options)<EOL>

format an options section using the INI format


for optname, optdict, value in options:<EOL><INDENT>value = _format_option_value(optdict, value)<EOL>help_opt = optdict.get("<STR_LIT>")<EOL>if help_opt:<EOL><INDENT>help_opt = normalize_text(help_opt, line_len=<NUM_LIT>, indent="<STR_LIT>")<EOL>print(file=stream)<EOL>print(help_opt, file=stream)<EOL><DEDENT>else:<EOL><INDENT>print(file=stream)<EOL><DEDENT>if value is None:<EOL><INDENT>print("<STR_LIT>" % optname, file=stream)<EOL><DEDENT>else:<EOL><INDENT>value = str(value).strip()<EOL>if re.match(r"<STR_LIT>", str(value)):<EOL><INDENT>separator = "<STR_LIT>" + "<STR_LIT:U+0020>" * len(optname)<EOL>value = separator.join(x + "<STR_LIT:U+002C>" for x in str(value).split("<STR_LIT:U+002C>"))<EOL>value = value[:-<NUM_LIT:1>]<EOL><DEDENT>print("<STR_LIT>" % (optname, value), file=stream)<EOL><DEDENT><DEDENT>


sched_getaffinity = getattr(os, "<STR_LIT>", None)<EOL>if sched_getaffinity:<EOL><INDENT>return len(sched_getaffinity(<NUM_LIT:0>))<EOL><DEDENT>if multiprocessing:<EOL><INDENT>return multiprocessing.cpu_count()<EOL><DEDENT>return <NUM_LIT:1><EOL>

Use sched_affinity if available for virtualized or containerized environments.


def report_total_messages_stats(sect, stats, previous_stats):

lines = ["<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>lines += checkers.table_lines_from_stats(<EOL>stats, previous_stats, ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT:error>")<EOL>)<EOL>sect.append(report_nodes.Table(children=lines, cols=<NUM_LIT:4>, rheaders=<NUM_LIT:1>))<EOL>


def report_messages_stats(sect, stats, _):

if not stats["<STR_LIT>"]:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>in_order = sorted(<EOL>[<EOL>(value, msg_id)<EOL>for msg_id, value in stats["<STR_LIT>"].items()<EOL>if not msg_id.startswith("<STR_LIT:I>")<EOL>]<EOL>)<EOL>in_order.reverse()<EOL>lines = ("<STR_LIT>", "<STR_LIT>")<EOL>for value, msg_id in in_order:<EOL><INDENT>lines += (msg_id, str(value))<EOL><DEDENT>sect.append(report_nodes.Table(children=lines, cols=<NUM_LIT:2>, rheaders=<NUM_LIT:1>))<EOL>


def report_messages_by_module_stats(sect, stats, _):

if len(stats["<STR_LIT>"]) == <NUM_LIT:1>:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>by_mod = collections.defaultdict(dict)<EOL>for m_type in ("<STR_LIT>", "<STR_LIT:error>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>total = stats[m_type]<EOL>for module in stats["<STR_LIT>"].keys():<EOL><INDENT>mod_total = stats["<STR_LIT>"][module][m_type]<EOL>if total == <NUM_LIT:0>:<EOL><INDENT>percent = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>percent = float((mod_total) * <NUM_LIT:100>) / total<EOL><DEDENT>by_mod[module][m_type] = percent<EOL><DEDENT><DEDENT>sorted_result = []<EOL>for module, mod_info in by_mod.items():<EOL><INDENT>sorted_result.append(<EOL>(<EOL>mod_info["<STR_LIT:error>"],<EOL>mod_info["<STR_LIT>"],<EOL>mod_info["<STR_LIT>"],<EOL>mod_info["<STR_LIT>"],<EOL>module,<EOL>)<EOL>)<EOL><DEDENT>sorted_result.sort()<EOL>sorted_result.reverse()<EOL>lines = ["<STR_LIT>", "<STR_LIT:error>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>for line in sorted_result:<EOL><INDENT>if all(entry == <NUM_LIT:0> for entry in line[:-<NUM_LIT:1>]):<EOL><INDENT>continue<EOL><DEDENT>lines.append(line[-<NUM_LIT:1>])<EOL>for val in line[:-<NUM_LIT:1>]:<EOL><INDENT>lines.append("<STR_LIT>" % val)<EOL><DEDENT><DEDENT>if len(lines) == <NUM_LIT:5>:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>sect.append(report_nodes.Table(children=lines, cols=<NUM_LIT:5>, rheaders=<NUM_LIT:1>))<EOL>

make errors / warnings by modules report


i = <NUM_LIT:0><EOL>while i < len(args):<EOL><INDENT>arg = args[i]<EOL>if arg.startswith("<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>option, val = arg[<NUM_LIT:2>:].split("<STR_LIT:=>", <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>option, val = arg[<NUM_LIT:2>:], None<EOL><DEDENT>try:<EOL><INDENT>cb, takearg = search_for[option]<EOL><DEDENT>except KeyError:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>del args[i]<EOL>if takearg and val is None:<EOL><INDENT>if i >= len(args) or args[i].startswith("<STR_LIT:->"):<EOL><INDENT>msg = "<STR_LIT>" % option<EOL>raise ArgumentPreprocessingError(msg)<EOL><DEDENT>val = args[i]<EOL>del args[i]<EOL><DEDENT>elif not takearg and val is not None:<EOL><INDENT>msg = "<STR_LIT>" % option<EOL>raise ArgumentPreprocessingError(msg)<EOL><DEDENT>cb(option, val)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>

look for some options (keys of <search_for>) which have to be processed
    before others

    values of <search_for> are callback functions to call when the option is
    found


orig = list(sys.path)<EOL>changes = []<EOL>for arg in args:<EOL><INDENT>path = _get_python_path(arg)<EOL>if path in changes:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>changes.append(path)<EOL><DEDENT><DEDENT>sys.path[:] = changes + ["<STR_LIT:.>"] + sys.path<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>sys.path[:] = orig<EOL><DEDENT>

Prepare sys.path for running the linter checks.

    Within this context, each of the given arguments is importable.
    Paths are added to sys.path in corresponding order to the arguments.
    We avoid adding duplicate directories to sys.path.
    `sys.path` is reset to its original value upon exiting this context.


exec(value)<EOL>

exec arbitrary code to set sys.path for instance


for modname in modnames:<EOL><INDENT>if modname in self._dynamic_plugins:<EOL><INDENT>continue<EOL><DEDENT>self._dynamic_plugins.add(modname)<EOL>module = modutils.load_module_from_name(modname)<EOL>module.register(self)<EOL><DEDENT>

take a list of module names which are pylint plugins and load
        and register them


for modname in self._dynamic_plugins:<EOL><INDENT>module = modutils.load_module_from_name(modname)<EOL>if hasattr(module, "<STR_LIT>"):<EOL><INDENT>module.load_configuration(self)<EOL><DEDENT><DEDENT>

Call the configuration hook for plugins

        This walks through the list of plugins, grabs the "load_configuration"
        hook, if exposed, and calls it to allow plugins to configure specific
        settings.


self.reporter = reporter<EOL>reporter.linter = self<EOL>

set the reporter used to display messages and reports


def set_option(self, optname, value, action=None, optdict=None):

if optname in self._options_methods or optname in self._bw_options_methods:<EOL><INDENT>if value:<EOL><INDENT>try:<EOL><INDENT>meth = self._options_methods[optname]<EOL><DEDENT>except KeyError:<EOL><INDENT>meth = self._bw_options_methods[optname]<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>% (optname, optname.split("<STR_LIT:->")[<NUM_LIT:0>]),<EOL>DeprecationWarning,<EOL>)<EOL><DEDENT>value = utils._check_csv(value)<EOL>if isinstance(value, (list, tuple)):<EOL><INDENT>for _id in value:<EOL><INDENT>meth(_id, ignore_unknown=True)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>meth(value)<EOL><DEDENT>return  <EOL><DEDENT><DEDENT>elif optname == "<STR_LIT>":<EOL><INDENT>self._reporter_name = value<EOL>if self._reporters:<EOL><INDENT>self._load_reporter()<EOL><DEDENT><DEDENT>try:<EOL><INDENT>checkers.BaseTokenChecker.set_option(self, optname, value, action, optdict)<EOL><DEDENT>except config.UnsupportedAction:<EOL><INDENT>print("<STR_LIT>" % optname, file=sys.stderr)<EOL><DEDENT>

overridden from config.OptionsProviderMixin to handle some
        special options


assert checker.priority <= <NUM_LIT:0>, "<STR_LIT>"<EOL>self._checkers[checker.name].append(checker)<EOL>for r_id, r_title, r_cb in checker.reports:<EOL><INDENT>self.register_report(r_id, r_title, r_cb, checker)<EOL><DEDENT>self.register_options_provider(checker)<EOL>if hasattr(checker, "<STR_LIT>"):<EOL><INDENT>self.msgs_store.register_messages_from_checker(checker)<EOL><DEDENT>checker.load_defaults()<EOL>if not getattr(checker, "<STR_LIT>", True):<EOL><INDENT>self.disable(checker.name)<EOL><DEDENT>

register a new checker

        checker is an object implementing IRawChecker or / and IAstroidChecker


for _reporters in self._reports.values():<EOL><INDENT>for report_id, _, _ in _reporters:<EOL><INDENT>self.disable_report(report_id)<EOL><DEDENT><DEDENT>


self._error_mode = True<EOL>self.disable_noerror_messages()<EOL>self.disable("<STR_LIT>")<EOL>if self._python3_porting_mode:<EOL><INDENT>self.disable("<STR_LIT:all>")<EOL>for msg_id in self._checker_messages("<STR_LIT>"):<EOL><INDENT>if msg_id.startswith("<STR_LIT:E>"):<EOL><INDENT>self.enable(msg_id)<EOL><DEDENT><DEDENT>config_parser = self.cfgfile_parser<EOL>if config_parser.has_option("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>value = config_parser.get("<STR_LIT>", "<STR_LIT>")<EOL>self.global_set_option("<STR_LIT>", value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.disable("<STR_LIT>")<EOL><DEDENT>self.set_option("<STR_LIT>", False)<EOL>self.set_option("<STR_LIT>", False)<EOL>self.set_option("<STR_LIT>", False)<EOL>

error mode: enable only errors; no reports, no persistent


self.disable("<STR_LIT:all>")<EOL>self.enable("<STR_LIT>")<EOL>if self._error_mode:<EOL><INDENT>for msg_id in self._checker_messages("<STR_LIT>"):<EOL><INDENT>if msg_id.startswith("<STR_LIT:E>"):<EOL><INDENT>self.enable(msg_id)<EOL><DEDENT>else:<EOL><INDENT>self.disable(msg_id)<EOL><DEDENT><DEDENT><DEDENT>config_parser = self.cfgfile_parser<EOL>if config_parser.has_option("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>value = config_parser.get("<STR_LIT>", "<STR_LIT>")<EOL>self.global_set_option("<STR_LIT>", value)<EOL><DEDENT>self._python3_porting_mode = True<EOL>

Disable all other checkers and enable Python 3 warnings.


control_pragmas = {"<STR_LIT>", "<STR_LIT>"}<EOL>for (tok_type, content, start, _, _) in tokens:<EOL><INDENT>if tok_type != tokenize.COMMENT:<EOL><INDENT>continue<EOL><DEDENT>match = OPTION_RGX.search(content)<EOL>if match is None:<EOL><INDENT>continue<EOL><DEDENT>first_group = match.group(<NUM_LIT:1>)<EOL>if (<EOL>first_group.strip() == "<STR_LIT>"<EOL>or first_group.strip() == "<STR_LIT>"<EOL>):<EOL><INDENT>if first_group.strip() == "<STR_LIT>":<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>line=start[<NUM_LIT:0>],<EOL>args=("<STR_LIT>", "<STR_LIT>"),<EOL>)<EOL><DEDENT>self.add_message("<STR_LIT>", line=start[<NUM_LIT:0>])<EOL>self._ignore_file = True<EOL>return<EOL><DEDENT>try:<EOL><INDENT>opt, value = first_group.split("<STR_LIT:=>", <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=first_group.strip(), line=start[<NUM_LIT:0>]<EOL>)<EOL>continue<EOL><DEDENT>opt = opt.strip()<EOL>if opt in self._options_methods or opt in self._bw_options_methods:<EOL><INDENT>try:<EOL><INDENT>meth = self._options_methods[opt]<EOL><DEDENT>except KeyError:<EOL><INDENT>meth = self._bw_options_methods[opt]<EOL>self.add_message(<EOL>"<STR_LIT>",<EOL>line=start[<NUM_LIT:0>],<EOL>args=(opt, opt.replace("<STR_LIT>", "<STR_LIT>")),<EOL>)<EOL><DEDENT>for msgid in utils._splitstrip(value):<EOL><INDENT>if opt in control_pragmas:<EOL><INDENT>self._pragma_lineno[msgid] = start[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>if (opt, msgid) == ("<STR_LIT>", "<STR_LIT:all>"):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>line=start[<NUM_LIT:0>],<EOL>args=("<STR_LIT>", "<STR_LIT>"),<EOL>)<EOL>self.add_message("<STR_LIT>", line=start[<NUM_LIT:0>])<EOL>self._ignore_file = True<EOL>return<EOL><DEDENT>meth(msgid, "<STR_LIT>", start[<NUM_LIT:0>])<EOL><DEDENT>except exceptions.UnknownMessageError:<EOL><INDENT>self.add_message("<STR_LIT>", args=msgid, line=start[<NUM_LIT:0>])<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", args=opt, line=start[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>

process tokens from the current module to search for module/block
        level options


return [self] + [<EOL>c<EOL>for _checkers in self._checkers.values()<EOL>for c in _checkers<EOL>if c is not self<EOL>]<EOL>


current_checkers = self.get_checkers()<EOL>return sorted(<EOL>{check.name for check in current_checkers if check.name != "<STR_LIT>"}<EOL>)<EOL>

Get all the checker names that this linter knows about.


if not self.config.reports:<EOL><INDENT>self.disable_reporters()<EOL><DEDENT>neededcheckers = [self]<EOL>for checker in self.get_checkers()[<NUM_LIT:1>:]:<EOL><INDENT>messages = {msg for msg in checker.msgs if self.is_message_enabled(msg)}<EOL>if messages or any(self.report_is_enabled(r[<NUM_LIT:0>]) for r in checker.reports):<EOL><INDENT>neededcheckers.append(checker)<EOL><DEDENT><DEDENT>neededcheckers = sorted(<EOL>neededcheckers, key=operator.attrgetter("<STR_LIT>"), reverse=True<EOL>)<EOL>return neededcheckers<EOL>

return checkers needed for activated messages and reports


@staticmethod<EOL><INDENT>def should_analyze_file(modname, path, is_argument=False):<DEDENT>

if is_argument:<EOL><INDENT>return True<EOL><DEDENT>return path.endswith("<STR_LIT>")<EOL>

Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :param bool is_argument: Whetter the file is an argument to pylint or not.
                                 Files which respect this property are always
                                 checked, since the user requested it explicitly.
        :returns: True if the module should be checked.
        :rtype: bool


<EOL>for msg in self.msgs_store.messages:<EOL><INDENT>if not msg.may_be_emitted():<EOL><INDENT>self._msgs_state[msg.msgid] = False<EOL><DEDENT><DEDENT>if not isinstance(files_or_modules, (list, tuple)):<EOL><INDENT>files_or_modules = (files_or_modules,)<EOL><DEDENT>if self.config.jobs == <NUM_LIT:1>:<EOL><INDENT>self._do_check(files_or_modules)<EOL><DEDENT>else:<EOL><INDENT>self._parallel_check(files_or_modules)<EOL><DEDENT>

main checking entry: check a list of files or modules from their
        name.


result, errors = utils.expand_modules(<EOL>modules, self.config.black_list, self.config.black_list_re<EOL>)<EOL>for error in errors:<EOL><INDENT>message = modname = error["<STR_LIT>"]<EOL>key = error["<STR_LIT:key>"]<EOL>self.set_current_module(modname)<EOL>if key == "<STR_LIT>":<EOL><INDENT>message = str(error["<STR_LIT>"]).replace(os.getcwd() + os.sep, "<STR_LIT>")<EOL><DEDENT>self.add_message(key, args=message)<EOL><DEDENT>return result<EOL>

get modules and errors from a list of modules and handle errors


def set_current_module(self, modname, filepath=None):

if not modname and filepath is None:<EOL><INDENT>return<EOL><DEDENT>self.reporter.on_set_current_module(modname, filepath)<EOL>self.current_name = modname<EOL>self.current_file = filepath or modname<EOL>self.stats["<STR_LIT>"][modname] = {}<EOL>self.stats["<STR_LIT>"][modname]["<STR_LIT>"] = <NUM_LIT:0><EOL>for msg_cat in MSG_TYPES.values():<EOL><INDENT>self.stats["<STR_LIT>"][modname][msg_cat] = <NUM_LIT:0><EOL><DEDENT>

set the name of the currently analyzed module and
        init statistics for it


try:<EOL><INDENT>return MANAGER.ast_from_file(filepath, modname, source=True)<EOL><DEDENT>except astroid.AstroidSyntaxError as ex:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", line=getattr(ex.error, "<STR_LIT>", <NUM_LIT:0>), args=str(ex.error)<EOL>)<EOL><DEDENT>except astroid.AstroidBuildingException as ex:<EOL><INDENT>self.add_message("<STR_LIT>", args=ex)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>import traceback<EOL>traceback.print_exc()<EOL>self.add_message("<STR_LIT>", args=(ex.__class__, ex))<EOL><DEDENT>

return an ast(roid) representation for a module


def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers):

try:<EOL><INDENT>tokens = utils.tokenize_module(ast_node)<EOL><DEDENT>except tokenize.TokenError as ex:<EOL><INDENT>self.add_message("<STR_LIT>", line=ex.args[<NUM_LIT:1>][<NUM_LIT:0>], args=ex.args[<NUM_LIT:0>])<EOL>return None<EOL><DEDENT>if not ast_node.pure_python:<EOL><INDENT>self.add_message("<STR_LIT>", args=ast_node.name)<EOL><DEDENT>else:<EOL><INDENT>self.process_tokens(tokens)<EOL>if self._ignore_file:<EOL><INDENT>return False<EOL><DEDENT>self.file_state.collect_block_lines(self.msgs_store, ast_node)<EOL>for checker in rawcheckers:<EOL><INDENT>checker.process_module(ast_node)<EOL><DEDENT>for checker in tokencheckers:<EOL><INDENT>checker.process_tokens(tokens)<EOL><DEDENT><DEDENT>walker.walk(ast_node)<EOL>return True<EOL>

Check a module from its astroid representation.


self.stats = {"<STR_LIT>": {}, "<STR_LIT>": {}}<EOL>MANAGER.always_load_extensions = self.config.unsafe_load_any_extension<EOL>MANAGER.max_inferable_values = self.config.limit_inference_results<EOL>MANAGER.extension_package_whitelist.update(self.config.extension_pkg_whitelist)<EOL>for msg_cat in MSG_TYPES.values():<EOL><INDENT>self.stats[msg_cat] = <NUM_LIT:0><EOL><DEDENT>


<EOL>self.reporter.display_messages(report_nodes.Section())<EOL>if self.file_state.base_name is not None:<EOL><INDENT>previous_stats = config.load_results(self.file_state.base_name)<EOL>self.reporter.on_close(self.stats, previous_stats)<EOL>if self.config.reports:<EOL><INDENT>sect = self.make_reports(self.stats, previous_stats)<EOL><DEDENT>else:<EOL><INDENT>sect = report_nodes.Section()<EOL><DEDENT>if self.config.reports:<EOL><INDENT>self.reporter.display_reports(sect)<EOL><DEDENT>self._report_evaluation()<EOL>if self.config.persistent:<EOL><INDENT>config.save_results(self.stats, self.file_state.base_name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.reporter.on_close(self.stats, {})<EOL><DEDENT>

close the whole package /module, it's time to make reports !

        if persistent run, pickle results for later comparison


<EOL>previous_stats = config.load_results(self.file_state.base_name)<EOL>if self.stats["<STR_LIT>"] == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>evaluation = self.config.evaluation<EOL>try:<EOL><INDENT>note = eval(evaluation, {}, self.stats)  <EOL><DEDENT>except Exception as ex:<EOL><INDENT>msg = "<STR_LIT>" % ex<EOL><DEDENT>else:<EOL><INDENT>self.stats["<STR_LIT>"] = note<EOL>msg = "<STR_LIT>" % note<EOL>pnote = previous_stats.get("<STR_LIT>")<EOL>if pnote is not None:<EOL><INDENT>msg += "<STR_LIT>" % (pnote, note - pnote)<EOL><DEDENT><DEDENT>if self.config.score:<EOL><INDENT>sect = report_nodes.EvaluationSection(msg)<EOL>self.reporter.display_reports(sect)<EOL><DEDENT>


self._rcfile = value<EOL>

callback for option preprocessing (i.e. before option parsing)


self._plugins.extend(utils._splitstrip(value))<EOL>


def cb_error_mode(self, *args, **kwargs):

error mode:
        * disable all but error messages
        * disable the 'miscellaneous' checker which can be safely deactivated in
          debug
        * disable reports
        * do not save execution information


def cb_generate_config(self, *args, **kwargs):

self.linter.generate_config(skipsections=("<STR_LIT>",))<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for sample config file generation


def cb_generate_manpage(self, *args, **kwargs):

from pylint import __pkginfo__<EOL>self.linter.generate_manpage(__pkginfo__)<EOL>sys.exit(<NUM_LIT:0>)<EOL>


def cb_help_message(self, option, optname, value, parser):

self.linter.msgs_store.help_message(utils._splitstrip(value))<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for printing some help about a particular message


def cb_full_documentation(self, option, optname, value, parser):

self.linter.print_full_documentation()<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for printing full documentation


def cb_list_messages(self, option, optname, value, parser):

self.linter.msgs_store.list_messages()<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for printing available messages


def cb_list_groups(self, *args, **kwargs):

for check in self.linter.get_checker_names():<EOL><INDENT>print(check)<EOL><DEDENT>sys.exit(<NUM_LIT:0>)<EOL>

List all the check groups that pylint knows about

        These should be useful to know what check groups someone can disable
        or enable.


def cb_python3_porting_mode(self, *args, **kwargs):

Activate only the python3 porting checker.


from pylint.lint import Run<EOL>try:<EOL><INDENT>Run(sys.argv[<NUM_LIT:1>:])<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>


from pylint.epylint import Run<EOL>Run()<EOL>


from pylint.pyreverse.main import Run<EOL>Run(sys.argv[<NUM_LIT:1>:])<EOL>


from pylint.checkers.similar import Run<EOL>Run(sys.argv[<NUM_LIT:1>:])<EOL>


def is_method_call(func, types=(), methods=()):

return (<EOL>isinstance(func, astroid.BoundMethod)<EOL>and isinstance(func.bound, astroid.Instance)<EOL>and (func.bound.name in types if types else True)<EOL>and (func.name in methods if methods else True)<EOL>)<EOL>

Determines if a BoundMethod node represents a method call.

    Args:
      func (astroid.BoundMethod): The BoundMethod AST node to check.
      types (Optional[String]): Optional sequence of caller type names to restrict check.
      methods (Optional[String]): Optional sequence of method names to restrict check.

    Returns:
      bool: true if the node represents a method call for the given type and
      method names, False otherwise.


inferred = utils.safe_infer(node)<EOL>if inferred is None or not isinstance(inferred.value, str):<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>parsed = list(string.Formatter().parse(inferred.value))<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>for _, _, format_spec, _ in parsed:<EOL><INDENT>if format_spec:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Checks if node represents a string with complex formatting specs.

    Args:
        node (astroid.node_classes.NodeNG): AST node to check
    Returns:
        bool: True if inferred string uses complex formatting, False otherwise


return sum(<NUM_LIT:1> for arg in args if not isinstance(arg, astroid.Keyword))<EOL>

Counts the number of tokens in an args list.

    The Python log functions allow for special keyword arguments: func,
    exc_info and extra. To handle these cases correctly, we only count
    arguments that aren't keywords.

    Args:
      args (list): AST nodes that are arguments for a log format string.

    Returns:
      int: Number of AST nodes that aren't keywords.


linter.register_checker(LoggingChecker(linter))<EOL>

Required method to auto-register this checker.


<EOL>self._logging_names = set()<EOL>logging_mods = self.config.logging_modules<EOL>self._format_style = self.config.logging_format_style<EOL>self._logging_modules = set(logging_mods)<EOL>self._from_imports = {}<EOL>for logging_mod in logging_mods:<EOL><INDENT>parts = logging_mod.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>if len(parts) > <NUM_LIT:1>:<EOL><INDENT>self._from_imports[parts[<NUM_LIT:0>]] = parts[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>

Clears any state left in this checker from last module checked.


try:<EOL><INDENT>logging_name = self._from_imports[node.modname]<EOL>for module, as_name in node.names:<EOL><INDENT>if module == logging_name:<EOL><INDENT>self._logging_names.add(as_name or module)<EOL><DEDENT><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>

Checks to see if a module uses a non-Python logging module.


for module, as_name in node.names:<EOL><INDENT>if module in self._logging_modules:<EOL><INDENT>self._logging_names.add(as_name or module)<EOL><DEDENT><DEDENT>

Checks to see if this module uses Python's built-in logging.


def is_logging_name():<EOL><INDENT>return (<EOL>isinstance(node.func, astroid.Attribute)<EOL>and isinstance(node.func.expr, astroid.Name)<EOL>and node.func.expr.name in self._logging_names<EOL>)<EOL><DEDENT>def is_logger_class():<EOL><INDENT>try:<EOL><INDENT>for inferred in node.func.infer():<EOL><INDENT>if isinstance(inferred, astroid.BoundMethod):<EOL><INDENT>parent = inferred._proxied.parent<EOL>if isinstance(parent, astroid.ClassDef) and (<EOL>parent.qname() == "<STR_LIT>"<EOL>or any(<EOL>ancestor.qname() == "<STR_LIT>"<EOL>for ancestor in parent.ancestors()<EOL>)<EOL>):<EOL><INDENT>return True, inferred._proxied.name<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except astroid.exceptions.InferenceError:<EOL><INDENT>pass<EOL><DEDENT>return False, None<EOL><DEDENT>if is_logging_name():<EOL><INDENT>name = node.func.attrname<EOL><DEDENT>else:<EOL><INDENT>result, name = is_logger_class()<EOL>if not result:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self._check_log_method(node, name)<EOL>


def _check_log_method(self, node, name):

if name == "<STR_LIT>":<EOL><INDENT>if node.starargs or node.kwargs or len(node.args) < <NUM_LIT:2>:<EOL><INDENT>return<EOL><DEDENT>format_pos = <NUM_LIT:1><EOL><DEDENT>elif name in CHECKED_CONVENIENCE_FUNCTIONS:<EOL><INDENT>if node.starargs or node.kwargs or not node.args:<EOL><INDENT>return<EOL><DEDENT>format_pos = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>if isinstance(node.args[format_pos], astroid.BinOp):<EOL><INDENT>binop = node.args[format_pos]<EOL>emit = binop.op == "<STR_LIT:%>"<EOL>if binop.op == "<STR_LIT:+>":<EOL><INDENT>total_number_of_strings = sum(<EOL><NUM_LIT:1><EOL>for operand in (binop.left, binop.right)<EOL>if self._is_operand_literal_str(utils.safe_infer(operand))<EOL>)<EOL>emit = total_number_of_strings > <NUM_LIT:0><EOL><DEDENT>if emit:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>elif isinstance(node.args[format_pos], astroid.Call):<EOL><INDENT>self._check_call_func(node.args[format_pos])<EOL><DEDENT>elif isinstance(node.args[format_pos], astroid.Const):<EOL><INDENT>self._check_format_string(node, format_pos)<EOL><DEDENT>elif isinstance(<EOL>node.args[format_pos], (astroid.FormattedValue, astroid.JoinedStr)<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Checks calls to logging.log(level, format, *format_args).


return isinstance(operand, astroid.Const) and operand.name == "<STR_LIT:str>"<EOL>

Return True if the operand in argument is a literal string


func = utils.safe_infer(node.func)<EOL>types = ("<STR_LIT:str>", "<STR_LIT>")<EOL>methods = ("<STR_LIT>",)<EOL>if is_method_call(func, types, methods) and not is_complex_format_str(<EOL>func.bound<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Checks that function call is not format_string.format().

        Args:
          node (astroid.node_classes.Call):
            Call AST node to be checked.


def _check_format_string(self, node, format_arg):

num_args = _count_supplied_tokens(node.args[format_arg + <NUM_LIT:1> :])<EOL>if not num_args:<EOL><INDENT>return<EOL><DEDENT>format_string = node.args[format_arg].value<EOL>if not isinstance(format_string, str):<EOL><INDENT>required_num_args = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if self._format_style == "<STR_LIT>":<EOL><INDENT>keyword_args, required_num_args, _, _ = utils.parse_format_string(<EOL>format_string<EOL>)<EOL>if keyword_args:<EOL><INDENT>return<EOL><DEDENT><DEDENT>elif self._format_style == "<STR_LIT>":<EOL><INDENT>keyword_arguments, implicit_pos_args, explicit_pos_args = utils.parse_format_method_string(<EOL>format_string<EOL>)<EOL>keyword_args_cnt = len(<EOL>set(k for k, l in keyword_arguments if not isinstance(k, int))<EOL>)<EOL>required_num_args = (<EOL>keyword_args_cnt + implicit_pos_args + explicit_pos_args<EOL>)<EOL><DEDENT><DEDENT>except utils.UnsupportedFormatCharacter as ex:<EOL><INDENT>char = format_string[ex.index]<EOL>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(char, ord(char), ex.index),<EOL>)<EOL>return<EOL><DEDENT>except utils.IncompleteFormatString:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT><DEDENT>if num_args > required_num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif num_args < required_num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Checks that format string tokens match the supplied arguments.

        Args:
          node (astroid.node_classes.NodeNG): AST node to be checked.
          format_arg (int): Index of the format string in the node arguments.


linter.register_checker(EncodingChecker(linter))<EOL>linter.register_checker(ByIdManagedMessagesChecker(linter))<EOL>

required method to auto register this checker


managed_msgs = MessagesHandlerMixIn.get_by_id_managed_msgs()<EOL>for (mod_name, msg_id, msg_symbol, lineno, is_disabled) in managed_msgs:<EOL><INDENT>if mod_name == module.name:<EOL><INDENT>if is_disabled:<EOL><INDENT>txt = "<STR_LIT>".format(<EOL>ident=msg_id, symbol=msg_symbol<EOL>)<EOL><DEDENT>else:<EOL><INDENT>txt = "<STR_LIT>".format(<EOL>ident=msg_id, symbol=msg_symbol<EOL>)<EOL><DEDENT>self.add_message("<STR_LIT>", line=lineno, args=txt)<EOL><DEDENT><DEDENT>MessagesHandlerMixIn.clear_by_id_managed_msgs()<EOL>

inspect the source file to find messages activated or deactivated by id.


if module.file_encoding:<EOL><INDENT>encoding = module.file_encoding<EOL><DEDENT>else:<EOL><INDENT>encoding = "<STR_LIT:ascii>"<EOL><DEDENT>with module.stream() as stream:<EOL><INDENT>for lineno, line in enumerate(stream):<EOL><INDENT>self._check_encoding(lineno + <NUM_LIT:1>, line, encoding)<EOL><DEDENT><DEDENT>

inspect the source file to find encoding problem


if not self.config.notes:<EOL><INDENT>return<EOL><DEDENT>comments = (<EOL>token_info for token_info in tokens if token_info.type == tokenize.COMMENT<EOL>)<EOL>for comment in comments:<EOL><INDENT>comment_text = comment.string[<NUM_LIT:1>:].lstrip()  <EOL>disable_option_match = OPTION_RGX.search(comment_text)<EOL>if disable_option_match:<EOL><INDENT>try:<EOL><INDENT>_, value = disable_option_match.group(<NUM_LIT:1>).split("<STR_LIT:=>", <NUM_LIT:1>)<EOL>values = [_val.strip().upper() for _val in value.split("<STR_LIT:U+002C>")]<EOL>if set(values) & set(self.config.notes):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>args=disable_option_match.group(<NUM_LIT:1>).strip(),<EOL>line=comment.string,<EOL>)<EOL>continue<EOL><DEDENT><DEDENT>match = self._fixme_pattern.search("<STR_LIT:#>" + comment_text.lower())<EOL>if match:<EOL><INDENT>note = match.group(<NUM_LIT:1>)<EOL>self.add_message(<EOL>"<STR_LIT>",<EOL>col_offset=comment.string.lower().index(note.lower()),<EOL>args=comment_text,<EOL>line=comment.start[<NUM_LIT:0>],<EOL>)<EOL><DEDENT><DEDENT>

inspect the source to find fixme problems


names = modname.split("<STR_LIT:.>")<EOL>return ["<STR_LIT:.>".join(names[<NUM_LIT:0> : i + <NUM_LIT:1>]) for i in range(len(names))]<EOL>

Split the names of the given module into subparts

    For example,
        _qualified_names('pylint.checkers.ImportsChecker')
    returns
        ['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker']


if isinstance(importnode, astroid.ImportFrom):<EOL><INDENT>if importnode.level:<EOL><INDENT>root = importnode.root()<EOL>if isinstance(root, astroid.Module):<EOL><INDENT>modname = root.relative_to_absolute_name(<EOL>modname, level=importnode.level<EOL>)<EOL><DEDENT><DEDENT><DEDENT>return modname<EOL>

Get a prepared module name from the given import node

    In the case of relative imports, this will return the
    absolute qualified module name, which might be useful
    for debugging. Otherwise, the initial module name
    is returned unchanged.


def _get_first_import(node, context, name, base, level, alias):

fullname = "<STR_LIT>" % (base, name) if base else name<EOL>first = None<EOL>found = False<EOL>for first in context.body:<EOL><INDENT>if first is node:<EOL><INDENT>continue<EOL><DEDENT>if first.scope() is node.scope() and first.fromlineno > node.fromlineno:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(first, astroid.Import):<EOL><INDENT>if any(fullname == iname[<NUM_LIT:0>] for iname in first.names):<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>elif isinstance(first, astroid.ImportFrom):<EOL><INDENT>if level == first.level:<EOL><INDENT>for imported_name, imported_alias in first.names:<EOL><INDENT>if fullname == "<STR_LIT>" % (first.modname, imported_name):<EOL><INDENT>found = True<EOL>break<EOL><DEDENT>if (<EOL>name != "<STR_LIT:*>"<EOL>and name == imported_name<EOL>and not (alias or imported_alias)<EOL>):<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if found:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if found and not astroid.are_exclusive(first, node):<EOL><INDENT>return first<EOL><DEDENT>return None<EOL>

return the node where [base.]<name> is imported or None if not found


tree_defs = {}<EOL>for mod, files in mod_files_list:<EOL><INDENT>node = (tree_defs, ())<EOL>for prefix in mod.split("<STR_LIT:.>"):<EOL><INDENT>node = node[<NUM_LIT:0>].setdefault(prefix, [{}, []])<EOL><DEDENT>node[<NUM_LIT:1>] += files<EOL><DEDENT>return tree_defs<EOL>

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


lines = []<EOL>nodes = data.items()<EOL>for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[<NUM_LIT:0>])):<EOL><INDENT>if not files:<EOL><INDENT>files = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>files = "<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(files))<EOL><DEDENT>if indent_str is None:<EOL><INDENT>lines.append("<STR_LIT>" % (mod, files))<EOL>sub_indent_str = "<STR_LIT:U+0020>"<EOL><DEDENT>else:<EOL><INDENT>lines.append(r"<STR_LIT>" % (indent_str, mod, files))<EOL>if i == len(nodes) - <NUM_LIT:1>:<EOL><INDENT>sub_indent_str = "<STR_LIT>" % indent_str<EOL><DEDENT>else:<EOL><INDENT>sub_indent_str = "<STR_LIT>" % indent_str<EOL><DEDENT><DEDENT>if sub:<EOL><INDENT>lines.append(_repr_tree_defs(sub, sub_indent_str))<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(lines)<EOL>

return a string which represents imports as a tree


done = {}<EOL>printer = DotBackend(filename[:-<NUM_LIT:4>], rankdir="<STR_LIT>")<EOL>printer.emit('<STR_LIT>')<EOL>for modname, dependencies in sorted(dep_info.items()):<EOL><INDENT>done[modname] = <NUM_LIT:1><EOL>printer.emit_node(modname)<EOL>for depmodname in dependencies:<EOL><INDENT>if depmodname not in done:<EOL><INDENT>done[depmodname] = <NUM_LIT:1><EOL>printer.emit_node(depmodname)<EOL><DEDENT><DEDENT><DEDENT>for depmodname, dependencies in sorted(dep_info.items()):<EOL><INDENT>for modname in dependencies:<EOL><INDENT>printer.emit_edge(modname, depmodname)<EOL><DEDENT><DEDENT>printer.generate(filename)<EOL>

write dependencies as a dot (graphviz) file


def _make_graph(filename, dep_info, sect, gtype):

_dependencies_graph(filename, dep_info)<EOL>sect.append(Paragraph("<STR_LIT>" % (gtype, filename)))<EOL>

generate a dependencies graph and add some information about it in the
    report's section


linter.register_checker(ImportsChecker(linter))<EOL>


self.linter.add_stats(dependencies={})<EOL>self.linter.add_stats(cycles=[])<EOL>self.stats = self.linter.stats<EOL>self.import_graph = collections.defaultdict(set)<EOL>self._module_pkg = {}  <EOL>self._excluded_edges = collections.defaultdict(set)<EOL>self._ignored_modules = get_global_option(self, "<STR_LIT>", default=[])<EOL>self.preferred_modules = dict(<EOL>module.split("<STR_LIT::>")<EOL>for module in self.config.preferred_modules<EOL>if "<STR_LIT::>" in module<EOL>)<EOL>

called before visiting project (i.e set of modules)


if self.linter.is_message_enabled("<STR_LIT>"):<EOL><INDENT>graph = self._import_graph_without_ignored_edges()<EOL>vertices = list(graph)<EOL>for cycle in get_cycles(graph, vertices=vertices):<EOL><INDENT>self.add_message("<STR_LIT>", args="<STR_LIT>".join(cycle))<EOL><DEDENT><DEDENT>


self._check_reimport(node)<EOL>self._check_import_as_rename(node)<EOL>modnode = node.root()<EOL>names = [name for name, _ in node.names]<EOL>if len(names) >= <NUM_LIT:2>:<EOL><INDENT>self.add_message("<STR_LIT>", args="<STR_LIT:U+002CU+0020>".join(names), node=node)<EOL><DEDENT>for name in names:<EOL><INDENT>self._check_deprecated_module(node, name)<EOL>self._check_preferred_module(node, name)<EOL>imported_module = self._get_imported_module(node, name)<EOL>if isinstance(node.parent, astroid.Module):<EOL><INDENT>self._check_position(node)<EOL><DEDENT>if isinstance(node.scope(), astroid.Module):<EOL><INDENT>self._record_import(node, imported_module)<EOL><DEDENT>if imported_module is None:<EOL><INDENT>continue<EOL><DEDENT>self._check_relative_import(modnode, node, imported_module, name)<EOL>self._add_imported_module(node, imported_module.name)<EOL><DEDENT>

triggered when an import statement is seen


basename = node.modname<EOL>imported_module = self._get_imported_module(node, basename)<EOL>self._check_import_as_rename(node)<EOL>self._check_misplaced_future(node)<EOL>self._check_deprecated_module(node, basename)<EOL>self._check_preferred_module(node, basename)<EOL>self._check_wildcard_imports(node, imported_module)<EOL>self._check_same_line_imports(node)<EOL>self._check_reimport(node, basename=basename, level=node.level)<EOL>if isinstance(node.parent, astroid.Module):<EOL><INDENT>self._check_position(node)<EOL><DEDENT>if isinstance(node.scope(), astroid.Module):<EOL><INDENT>self._record_import(node, imported_module)<EOL><DEDENT>if imported_module is None:<EOL><INDENT>return<EOL><DEDENT>modnode = node.root()<EOL>self._check_relative_import(modnode, node, imported_module, basename)<EOL>for name, _ in node.names:<EOL><INDENT>if name != "<STR_LIT:*>":<EOL><INDENT>self._add_imported_module(node, "<STR_LIT>" % (imported_module.name, name))<EOL><DEDENT>else:<EOL><INDENT>self._add_imported_module(node, imported_module.name)<EOL><DEDENT><DEDENT>


<EOL>if self._first_non_import_node:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=node.as_string())<EOL><DEDENT>

Check `node` import or importfrom node position is correct

        Send a message  if `node` comes before another instruction


def _record_import(self, node, importedmodnode):

if isinstance(node, astroid.ImportFrom):<EOL><INDENT>importedname = node.modname<EOL><DEDENT>else:<EOL><INDENT>importedname = importedmodnode.name if importedmodnode else None<EOL><DEDENT>if not importedname:<EOL><INDENT>importedname = node.names[<NUM_LIT:0>][<NUM_LIT:0>].split("<STR_LIT:.>")[<NUM_LIT:0>]<EOL><DEDENT>if isinstance(node, astroid.ImportFrom) and (node.level or <NUM_LIT:0>) >= <NUM_LIT:1>:<EOL><INDENT>importedname = "<STR_LIT:.>" + importedname<EOL><DEDENT>self._imports_stack.append((node, importedname))<EOL>


std_imports = []<EOL>third_party_imports = []<EOL>first_party_imports = []<EOL>external_imports = []<EOL>local_imports = []<EOL>third_party_not_ignored = []<EOL>first_party_not_ignored = []<EOL>local_not_ignored = []<EOL>isort_obj = isort.SortImports(<EOL>file_contents="<STR_LIT>",<EOL>known_third_party=self.config.known_third_party,<EOL>known_standard_library=self.config.known_standard_library,<EOL>)<EOL>for node, modname in self._imports_stack:<EOL><INDENT>if modname.startswith("<STR_LIT:.>"):<EOL><INDENT>package = "<STR_LIT:.>" + modname.split("<STR_LIT:.>")[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>package = modname.split("<STR_LIT:.>")[<NUM_LIT:0>]<EOL><DEDENT>nested = not isinstance(node.parent, astroid.Module)<EOL>ignore_for_import_order = not self.linter.is_message_enabled(<EOL>"<STR_LIT>", node.fromlineno<EOL>)<EOL>import_category = isort_obj.place_module(package)<EOL>node_and_package_import = (node, package)<EOL>if import_category in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>std_imports.append(node_and_package_import)<EOL>wrong_import = (<EOL>third_party_not_ignored<EOL>or first_party_not_ignored<EOL>or local_not_ignored<EOL>)<EOL>if self._is_fallback_import(node, wrong_import):<EOL><INDENT>continue<EOL><DEDENT>if wrong_import and not nested:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(<EOL>'<STR_LIT>' % node.as_string(),<EOL>'<STR_LIT>' % wrong_import[<NUM_LIT:0>][<NUM_LIT:0>].as_string(),<EOL>),<EOL>)<EOL><DEDENT><DEDENT>elif import_category == "<STR_LIT>":<EOL><INDENT>third_party_imports.append(node_and_package_import)<EOL>external_imports.append(node_and_package_import)<EOL>if not nested and not ignore_for_import_order:<EOL><INDENT>third_party_not_ignored.append(node_and_package_import)<EOL><DEDENT>wrong_import = first_party_not_ignored or local_not_ignored<EOL>if wrong_import and not nested:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(<EOL>'<STR_LIT>' % node.as_string(),<EOL>'<STR_LIT>' % wrong_import[<NUM_LIT:0>][<NUM_LIT:0>].as_string(),<EOL>),<EOL>)<EOL><DEDENT><DEDENT>elif import_category == "<STR_LIT>":<EOL><INDENT>first_party_imports.append(node_and_package_import)<EOL>external_imports.append(node_and_package_import)<EOL>if not nested and not ignore_for_import_order:<EOL><INDENT>first_party_not_ignored.append(node_and_package_import)<EOL><DEDENT>wrong_import = local_not_ignored<EOL>if wrong_import and not nested:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(<EOL>'<STR_LIT>' % node.as_string(),<EOL>'<STR_LIT>' % wrong_import[<NUM_LIT:0>][<NUM_LIT:0>].as_string(),<EOL>),<EOL>)<EOL><DEDENT><DEDENT>elif import_category == "<STR_LIT>":<EOL><INDENT>local_imports.append((node, package))<EOL>if not nested and not ignore_for_import_order:<EOL><INDENT>local_not_ignored.append((node, package))<EOL><DEDENT><DEDENT><DEDENT>return std_imports, external_imports, local_imports<EOL>

Checks imports of module `node` are grouped by category

        Imports must follow this order: standard, 3rd party, local


def _check_relative_import(<EOL>self, modnode, importnode, importedmodnode, importedasname<EOL>):

if not self.linter.is_message_enabled("<STR_LIT>"):<EOL><INDENT>return None<EOL><DEDENT>if importedmodnode.file is None:<EOL><INDENT>return False  <EOL><DEDENT>if modnode is importedmodnode:<EOL><INDENT>return False  <EOL><DEDENT>if modnode.absolute_import_activated() or getattr(importnode, "<STR_LIT>", None):<EOL><INDENT>return False<EOL><DEDENT>if importedmodnode.name != importedasname:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>args=(importedasname, importedmodnode.name),<EOL>node=importnode,<EOL>)<EOL>return None<EOL><DEDENT>return None<EOL>

check relative import. node is either an Import or From node, modname
        the imported module name.


def _add_imported_module(self, node, importedmodname):

module_file = node.root().file<EOL>context_name = node.root().name<EOL>base = os.path.splitext(os.path.basename(module_file))[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>importedmodname = astroid.modutils.get_module_part(<EOL>importedmodname, module_file<EOL>)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>if context_name == importedmodname:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif not astroid.modutils.is_standard_module(importedmodname):<EOL><INDENT>if base != "<STR_LIT>" and context_name not in self._module_pkg:<EOL><INDENT>self._module_pkg[context_name] = context_name.rsplit("<STR_LIT:.>", <NUM_LIT:1>)[<NUM_LIT:0>]<EOL><DEDENT>importedmodnames = self.stats["<STR_LIT>"].setdefault(<EOL>importedmodname, set()<EOL>)<EOL>if context_name not in importedmodnames:<EOL><INDENT>importedmodnames.add(context_name)<EOL><DEDENT>self.import_graph[context_name].add(importedmodname)<EOL>if not self.linter.is_message_enabled("<STR_LIT>", line=node.lineno):<EOL><INDENT>self._excluded_edges[context_name].add(importedmodname)<EOL><DEDENT><DEDENT>

notify an imported module, used to analyze dependencies


def _check_deprecated_module(self, node, mod_path):

for mod_name in self.config.deprecated_modules:<EOL><INDENT>if mod_path == mod_name or mod_path.startswith(mod_name + "<STR_LIT:.>"):<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=mod_path)<EOL><DEDENT><DEDENT>


def _check_preferred_module(self, node, mod_path):

if mod_path in self.preferred_modules:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(self.preferred_modules[mod_path], mod_path),<EOL>)<EOL><DEDENT>

check if the module has a preferred replacement


def _check_reimport(self, node, basename=None, level=None):

if not self.linter.is_message_enabled("<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>frame = node.frame()<EOL>root = node.root()<EOL>contexts = [(frame, level)]<EOL>if root is not frame:<EOL><INDENT>contexts.append((root, None))<EOL><DEDENT>for known_context, known_level in contexts:<EOL><INDENT>for name, alias in node.names:<EOL><INDENT>first = _get_first_import(<EOL>node, known_context, name, basename, known_level, alias<EOL>)<EOL>if first is not None:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(name, first.fromlineno)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>

check if the import is necessary (i.e. not already done)


def _report_external_dependencies(self, sect, _, _dummy):

dep_info = _make_tree_defs(self._external_dependencies_info().items())<EOL>if not dep_info:<EOL><INDENT>raise EmptyReportError()<EOL><DEDENT>tree_str = _repr_tree_defs(dep_info)<EOL>sect.append(VerbatimText(tree_str))<EOL>

return a verbatim layout for displaying dependencies


def _report_dependencies_graph(self, sect, _, _dummy):

dep_info = self.stats["<STR_LIT>"]<EOL>if not dep_info or not (<EOL>self.config.import_graph<EOL>or self.config.ext_import_graph<EOL>or self.config.int_import_graph<EOL>):<EOL><INDENT>raise EmptyReportError()<EOL><DEDENT>filename = self.config.import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, dep_info, sect, "<STR_LIT>")<EOL><DEDENT>filename = self.config.ext_import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, self._external_dependencies_info(), sect, "<STR_LIT>")<EOL><DEDENT>filename = self.config.int_import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, self._internal_dependencies_info(), sect, "<STR_LIT>")<EOL><DEDENT>


graph = collections.defaultdict(set)<EOL>for importee, importers in self.stats["<STR_LIT>"].items():<EOL><INDENT>for importer in importers:<EOL><INDENT>package = self._module_pkg.get(importer, importer)<EOL>is_inside = importee.startswith(package)<EOL>if is_inside and internal or not is_inside and not internal:<EOL><INDENT>graph[importee].add(importer)<EOL><DEDENT><DEDENT><DEDENT>return graph<EOL>

build the internal or the external depedency graph


return self._filter_dependencies_graph(internal=False)<EOL>

return cached external dependencies information or build and
        cache them


return self._filter_dependencies_graph(internal=True)<EOL>

return cached internal dependencies information or build and
        cache them


try:<EOL><INDENT>module = stmt.do_import_module(stmt.modname)<EOL><DEDENT>except astroid.AstroidBuildingException:<EOL><INDENT>return None<EOL><DEDENT>for local_node in module.locals.get(name, []):<EOL><INDENT>if isinstance(local_node, astroid.ImportFrom) and local_node.modname == FUTURE:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return None<EOL>

Check if the name is a future import from another module.


return isinstance(parent, astroid.For) and any(<EOL>else_stmt.parent_of(stmt) or else_stmt == stmt for else_stmt in parent.orelse<EOL>)<EOL>

Returns True if stmt in inside the else branch for a parent For stmt.


try:<EOL><INDENT>parent = next(klass.local_attr_ancestors(name))<EOL><DEDENT>except (StopIteration, KeyError):<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>meth_node = parent[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(meth_node, astroid.FunctionDef):<EOL><INDENT>return meth_node<EOL><DEDENT>return None<EOL>


more = "<STR_LIT>"<EOL>infered_module = infered.root().name<EOL>if node.root().name == infered_module:<EOL><INDENT>if node.lineno == infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % infered.as_string()<EOL><DEDENT>elif infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % infered.lineno<EOL><DEDENT><DEDENT>elif infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % (infered.lineno, infered_module)<EOL><DEDENT>return more<EOL>

return extra information to add to the message for unpacking-non-sequence
    and unbalanced-tuple-unpacking errors


def _detect_global_scope(node, frame, defframe):

def_scope = scope = None<EOL>if frame and frame.parent:<EOL><INDENT>scope = frame.parent.scope()<EOL><DEDENT>if defframe and defframe.parent:<EOL><INDENT>def_scope = defframe.parent.scope()<EOL><DEDENT>if isinstance(frame, astroid.FunctionDef):<EOL><INDENT>if not isinstance(node.parent, (astroid.FunctionDef, astroid.Arguments)):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif any(<EOL>not isinstance(f, (astroid.ClassDef, astroid.Module)) for f in (frame, defframe)<EOL>):<EOL><INDENT>return False<EOL><DEDENT>break_scopes = []<EOL>for s in (scope, def_scope):<EOL><INDENT>parent_scope = s<EOL>while parent_scope:<EOL><INDENT>if not isinstance(parent_scope, (astroid.ClassDef, astroid.Module)):<EOL><INDENT>break_scopes.append(parent_scope)<EOL>break<EOL><DEDENT>if parent_scope.parent:<EOL><INDENT>parent_scope = parent_scope.parent.scope()<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if break_scopes and len(set(break_scopes)) != <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>return frame.lineno < defframe.lineno<EOL>

Detect that the given frames shares a global
    scope.

    Two frames shares a global scope when neither
    of them are hidden under a function scope, as well
    as any of parent scope of them, until the root scope.
    In this case, depending from something defined later on
    will not work, because it is still undefined.

    Example:
        class A:
            # B has the same global scope as `C`, leading to a NameError.
            class B(C): ...
        class C: ...


<EOL>names = {}<EOL>for name, stmts in not_consumed.items():<EOL><INDENT>if any(<EOL>isinstance(stmt, astroid.AssignName)<EOL>and isinstance(stmt.assign_type(), astroid.AugAssign)<EOL>for stmt in stmts<EOL>):<EOL><INDENT>continue<EOL><DEDENT>for stmt in stmts:<EOL><INDENT>if not isinstance(stmt, (astroid.ImportFrom, astroid.Import)):<EOL><INDENT>continue<EOL><DEDENT>for imports in stmt.names:<EOL><INDENT>second_name = None<EOL>import_module_name = imports[<NUM_LIT:0>]<EOL>if import_module_name == "<STR_LIT:*>":<EOL><INDENT>second_name = name<EOL><DEDENT>else:<EOL><INDENT>name_matches_dotted_import = False<EOL>if (<EOL>import_module_name.startswith(name)<EOL>and import_module_name.find("<STR_LIT:.>") > -<NUM_LIT:1><EOL>):<EOL><INDENT>name_matches_dotted_import = True<EOL><DEDENT>if name_matches_dotted_import or name in imports:<EOL><INDENT>second_name = import_module_name<EOL><DEDENT><DEDENT>if second_name and second_name not in names:<EOL><INDENT>names[second_name] = stmt<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return sorted(names.items(), key=lambda a: a[<NUM_LIT:1>].fromlineno)<EOL>

Try to fix imports with multiple dots, by returning a dictionary
    with the import names expanded. The function unflattens root imports,
    like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
    and 'xml.sax' respectively.


imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))<EOL>for import_node in imports:<EOL><INDENT>for import_name, import_alias in import_node.names:<EOL><INDENT>if import_alias:<EOL><INDENT>if import_alias == name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif import_name and import_name == name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>

Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.


assign_stmts = name_node.scope().nodes_of_class(astroid.AssignName)<EOL>return any(a.name == name_node.name for a in assign_stmts)<EOL>

Checks if name_node has corresponding assign statement in same scope


linter.register_checker(VariablesChecker(linter))<EOL>

required method to auto register this checker


def mark_as_consumed(self, name, new_node):

self.consumed[name] = new_node<EOL>del self.to_consume[name]<EOL>

Mark the name as consumed and delete it from
the to_consume dictionary


self._to_consume = [NamesConsumer(node, "<STR_LIT>")]<EOL>self._postponed_evaluation_enabled = is_postponed_evaluation_enabled(node)<EOL>for name, stmts in node.locals.items():<EOL><INDENT>if utils.is_builtin(name) and not utils.is_inside_except(stmts[<NUM_LIT:0>]):<EOL><INDENT>if self._should_ignore_redefined_builtin(stmts[<NUM_LIT:0>]) or name == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>self.add_message("<STR_LIT>", args=name, node=stmts[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>

visit module : update consumption analysis variable
        checks globals doesn't overrides builtins


assert len(self._to_consume) == <NUM_LIT:1><EOL>not_consumed = self._to_consume.pop().to_consume<EOL>if "<STR_LIT>" in node.locals:<EOL><INDENT>self._check_all(node, not_consumed)<EOL><DEDENT>self._check_globals(not_consumed)<EOL>if not self.config.init_import and node.package:<EOL><INDENT>return<EOL><DEDENT>self._check_imports(not_consumed)<EOL>


self._to_consume.append(NamesConsumer(node, "<STR_LIT:class>"))<EOL>

visit class: update consumption analysis variable


leave class: update consumption analysis variable


self._to_consume.append(NamesConsumer(node, "<STR_LIT>"))<EOL>

visit lambda: update consumption analysis variable


leave lambda: update consumption analysis variable


visit genexpr: update consumption analysis variable


leave genexpr: update consumption analysis variable


visit dictcomp: update consumption analysis variable


leave dictcomp: update consumption analysis variable


visit setcomp: update consumption analysis variable


leave setcomp: update consumption analysis variable


self._to_consume.append(NamesConsumer(node, "<STR_LIT>"))<EOL>if not (<EOL>self.linter.is_message_enabled("<STR_LIT>")<EOL>or self.linter.is_message_enabled("<STR_LIT>")<EOL>):<EOL><INDENT>return<EOL><DEDENT>globs = node.root().globals<EOL>for name, stmt in node.items():<EOL><INDENT>if utils.is_inside_except(stmt):<EOL><INDENT>continue<EOL><DEDENT>if name in globs and not isinstance(stmt, astroid.Global):<EOL><INDENT>definition = globs[name][<NUM_LIT:0>]<EOL>if (<EOL>isinstance(definition, astroid.ImportFrom)<EOL>and definition.modname == FUTURE<EOL>):<EOL><INDENT>continue<EOL><DEDENT>line = definition.fromlineno<EOL>if not self._is_name_ignored(stmt, name):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=(name, line), node=stmt<EOL>)<EOL><DEDENT><DEDENT>elif utils.is_builtin(name) and not self._should_ignore_redefined_builtin(<EOL>stmt<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", args=name, node=stmt)<EOL><DEDENT><DEDENT>

visit function: update consumption analysis variable and check locals


if node.type_comment_returns:<EOL><INDENT>self._store_type_annotation_node(node.type_comment_returns)<EOL><DEDENT>if node.type_comment_args:<EOL><INDENT>for argument_annotation in node.type_comment_args:<EOL><INDENT>self._store_type_annotation_node(argument_annotation)<EOL><DEDENT><DEDENT>not_consumed = self._to_consume.pop().to_consume<EOL>if not (<EOL>self.linter.is_message_enabled("<STR_LIT>")<EOL>or self.linter.is_message_enabled("<STR_LIT>")<EOL>or self.linter.is_message_enabled("<STR_LIT>")<EOL>):<EOL><INDENT>return<EOL><DEDENT>if utils.is_error(node):<EOL><INDENT>return<EOL><DEDENT>is_method = node.is_method()<EOL>if is_method and node.is_abstract():<EOL><INDENT>return<EOL><DEDENT>global_names = _flattened_scope_names(node.nodes_of_class(astroid.Global))<EOL>nonlocal_names = _flattened_scope_names(node.nodes_of_class(astroid.Nonlocal))<EOL>for name, stmts in not_consumed.items():<EOL><INDENT>self._check_is_unused(name, node, stmts[<NUM_LIT:0>], global_names, nonlocal_names)<EOL><DEDENT>

leave function: check function's locals are consumed


frame = node.frame()<EOL>if isinstance(frame, astroid.Module):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>module = frame.root()<EOL>default_message = True<EOL>locals_ = node.scope().locals<EOL>for name in node.names:<EOL><INDENT>try:<EOL><INDENT>assign_nodes = module.getattr(name)<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>assign_nodes = []<EOL><DEDENT>not_defined_locally_by_import = not any(<EOL>isinstance(local, astroid.node_classes.Import)<EOL>for local in locals_.get(name, ())<EOL>)<EOL>if not assign_nodes and not_defined_locally_by_import:<EOL><INDENT>self.add_message("<STR_LIT>", args=name, node=node)<EOL>default_message = False<EOL>continue<EOL><DEDENT>for anode in assign_nodes:<EOL><INDENT>if (<EOL>isinstance(anode, astroid.AssignName)<EOL>and anode.name in module.special_attributes<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", args=name, node=node)<EOL>break<EOL><DEDENT>if anode.frame() is module:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not_defined_locally_by_import:<EOL><INDENT>self.add_message("<STR_LIT>", args=name, node=node)<EOL>default_message = False<EOL><DEDENT><DEDENT><DEDENT>if default_message:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

check names imported exists in the global scope


<EOL>name = node.name<EOL>frame = node.statement().scope()<EOL>in_annotation_or_default = self._defined_in_function_definition(node, frame)<EOL>if in_annotation_or_default:<EOL><INDENT>frame_locals = frame.parent.scope().locals<EOL><DEDENT>else:<EOL><INDENT>frame_locals = frame.locals<EOL><DEDENT>return not (<EOL>(isinstance(frame, astroid.ClassDef) or in_annotation_or_default)<EOL>and name in frame_locals<EOL>)<EOL>

Return True if the node is in a local class scope, as an assignment.

:param node: Node considered
:type node: astroid.Node
:return: True if the node is in a local class scope, as an assignment. False otherwise.
:rtype: bool


stmt = node.statement()<EOL>if stmt.fromlineno is None:<EOL><INDENT>assert not stmt.root().file.endswith("<STR_LIT>")<EOL>return<EOL><DEDENT>name = node.name<EOL>frame = stmt.scope()<EOL>if (<EOL>utils.is_default_argument(node)<EOL>or utils.is_func_decorator(node)<EOL>or utils.is_ancestor_name(frame, node)<EOL>):<EOL><INDENT>start_index = len(self._to_consume) - <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>start_index = len(self._to_consume) - <NUM_LIT:1><EOL><DEDENT>base_scope_type = self._to_consume[start_index].scope_type<EOL>for i in range(start_index, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>current_consumer = self._to_consume[i]<EOL>if (<EOL>current_consumer.scope_type == "<STR_LIT:class>"<EOL>and i != start_index<EOL>and not (base_scope_type == "<STR_LIT>" and i == start_index - <NUM_LIT:1>)<EOL>):<EOL><INDENT>if self._ignore_class_scope(node):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if name in current_consumer.consumed and not (<EOL>current_consumer.scope_type == "<STR_LIT>"<EOL>and self._has_homonym_in_upper_function_scope(node, i)<EOL>):<EOL><INDENT>defnode = utils.assign_parent(current_consumer.consumed[name][<NUM_LIT:0>])<EOL>self._check_late_binding_closure(node, defnode)<EOL>self._loopvar_name(node, name)<EOL>break<EOL><DEDENT>found_node = current_consumer.get_next_to_consume(node)<EOL>if found_node is None:<EOL><INDENT>continue<EOL><DEDENT>defnode = utils.assign_parent(current_consumer.to_consume[name][<NUM_LIT:0>])<EOL>if defnode is not None:<EOL><INDENT>self._check_late_binding_closure(node, defnode)<EOL>defstmt = defnode.statement()<EOL>defframe = defstmt.frame()<EOL>recursive_klass = (<EOL>frame is defframe<EOL>and defframe.parent_of(node)<EOL>and isinstance(defframe, astroid.ClassDef)<EOL>and node.name == defframe.name<EOL>)<EOL>if (<EOL>recursive_klass<EOL>and utils.is_inside_lambda(node)<EOL>and (<EOL>not utils.is_default_argument(node)<EOL>or node.scope().parent.scope() is not defframe<EOL>)<EOL>):<EOL><INDENT>break<EOL><DEDENT>maybee0601, annotation_return, use_outer_definition = self._is_variable_violation(<EOL>node,<EOL>name,<EOL>defnode,<EOL>stmt,<EOL>defstmt,<EOL>frame,<EOL>defframe,<EOL>base_scope_type,<EOL>recursive_klass,<EOL>)<EOL>if use_outer_definition:<EOL><INDENT>continue<EOL><DEDENT>if (<EOL>maybee0601<EOL>and not utils.is_defined_before(node)<EOL>and not astroid.are_exclusive(stmt, defstmt, ("<STR_LIT>",))<EOL>):<EOL><INDENT>defined_by_stmt = defstmt is stmt and isinstance(<EOL>node, (astroid.DelName, astroid.AssignName)<EOL>)<EOL>if (<EOL>recursive_klass<EOL>or defined_by_stmt<EOL>or annotation_return<EOL>or isinstance(defstmt, astroid.Delete)<EOL>):<EOL><INDENT>if not utils.node_ignores_exception(node, NameError):<EOL><INDENT>if not (<EOL>self._postponed_evaluation_enabled<EOL>and isinstance(<EOL>stmt,<EOL>(<EOL>astroid.AnnAssign,<EOL>astroid.FunctionDef,<EOL>astroid.Arguments,<EOL>),<EOL>)<EOL>and name in node.root().locals<EOL>):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=name, node=node<EOL>)<EOL><DEDENT><DEDENT><DEDENT>elif base_scope_type != "<STR_LIT>":<EOL><INDENT>if not (<EOL>self._postponed_evaluation_enabled<EOL>and isinstance(<EOL>stmt, (astroid.AnnAssign, astroid.FunctionDef)<EOL>)<EOL>):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=name, node=node<EOL>)<EOL><DEDENT><DEDENT>elif base_scope_type == "<STR_LIT>":<EOL><INDENT>if isinstance(frame, astroid.ClassDef) and name in frame.locals:<EOL><INDENT>if isinstance(node.parent, astroid.Arguments):<EOL><INDENT>if stmt.fromlineno <= defstmt.fromlineno:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=name, node=node<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=name, node=node<EOL>)<EOL><DEDENT><DEDENT>elif current_consumer.scope_type == "<STR_LIT>":<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=name)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>current_consumer.mark_as_consumed(name, found_node)<EOL>self._loopvar_name(node, name)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>if not (<EOL>name in astroid.Module.scope_attrs<EOL>or utils.is_builtin(name)<EOL>or name in self.config.additional_builtins<EOL>):<EOL><INDENT>if not utils.node_ignores_exception(node, NameError):<EOL><INDENT>self.add_message("<STR_LIT>", args=name, node=node)<EOL><DEDENT><DEDENT><DEDENT>

check that a name is defined if the current scope and doesn't
        redefine a built-in


def _has_homonym_in_upper_function_scope(self, node, index):

for _consumer in self._to_consume[index - <NUM_LIT:1> :: -<NUM_LIT:1>]:<EOL><INDENT>if _consumer.scope_type == "<STR_LIT>" and node.name in _consumer.to_consume:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return True if there is a node with the same name in the to_consume dict of an upper scope
and if that scope is a function

:param node: node to check for
:type node: astroid.Node
:param index: index of the current consumer inside self._to_consume
:type index: int
:return: True if there is a node with the same name in the to_consume dict of an upper scope
         and if that scope is a function
:rtype: bool


if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):<EOL><INDENT>return<EOL><DEDENT>for name, _ in node.names:<EOL><INDENT>parts = name.split("<STR_LIT:.>")<EOL>try:<EOL><INDENT>module = next(_infer_name_module(node, parts[<NUM_LIT:0>]))<EOL><DEDENT>except astroid.ResolveError:<EOL><INDENT>continue<EOL><DEDENT>self._check_module_attrs(node, module, parts[<NUM_LIT:1>:])<EOL><DEDENT>


if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):<EOL><INDENT>return<EOL><DEDENT>name_parts = node.modname.split("<STR_LIT:.>")<EOL>try:<EOL><INDENT>module = node.do_import_module(name_parts[<NUM_LIT:0>])<EOL><DEDENT>except astroid.AstroidBuildingException:<EOL><INDENT>return<EOL><DEDENT>module = self._check_module_attrs(node, module, name_parts[<NUM_LIT:1>:])<EOL>if not module:<EOL><INDENT>return<EOL><DEDENT>for name, _ in node.names:<EOL><INDENT>if name == "<STR_LIT:*>":<EOL><INDENT>continue<EOL><DEDENT>self._check_module_attrs(node, module, name.split("<STR_LIT:.>"))<EOL><DEDENT>


@utils.check_messages(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"<EOL>)<EOL><INDENT>def visit_assign(self, node):<DEDENT>

self._check_self_cls_assign(node)<EOL>if not isinstance(node.targets[<NUM_LIT:0>], (astroid.Tuple, astroid.List)):<EOL><INDENT>return<EOL><DEDENT>targets = node.targets[<NUM_LIT:0>].itered()<EOL>try:<EOL><INDENT>infered = utils.safe_infer(node.value)<EOL>if infered is not None:<EOL><INDENT>self._check_unpacking(infered, node, targets)<EOL><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>

Check unbalanced tuple unpacking for assignments
        and unpacking non-sequences as well as in case self/cls
        get assigned.


assign_names = {<EOL>target.name<EOL>for target in node.targets<EOL>if isinstance(target, astroid.AssignName)<EOL>}<EOL>scope = node.scope()<EOL>nonlocals_with_same_name = any(<EOL>child<EOL>for child in scope.body<EOL>if isinstance(child, astroid.Nonlocal) and assign_names & set(child.names)<EOL>)<EOL>if nonlocals_with_same_name:<EOL><INDENT>scope = node.scope().parent.scope()<EOL><DEDENT>if not (<EOL>isinstance(scope, astroid.scoped_nodes.FunctionDef)<EOL>and scope.is_method()<EOL>and "<STR_LIT>" not in scope.decoratornames()<EOL>):<EOL><INDENT>return<EOL><DEDENT>argument_names = scope.argnames()<EOL>if not argument_names:<EOL><INDENT>return<EOL><DEDENT>self_cls_name = argument_names[<NUM_LIT:0>]<EOL>target_assign_names = (<EOL>target.name<EOL>for target in node.targets<EOL>if isinstance(target, astroid.node_classes.AssignName)<EOL>)<EOL>if self_cls_name in target_assign_names:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=(self_cls_name))<EOL><DEDENT>


def _check_unpacking(self, infered, node, targets):

if utils.is_inside_abstract_class(node):<EOL><INDENT>return<EOL><DEDENT>if utils.is_comprehension(node):<EOL><INDENT>return<EOL><DEDENT>if infered is astroid.Uninferable:<EOL><INDENT>return<EOL><DEDENT>if (<EOL>isinstance(infered.parent, astroid.Arguments)<EOL>and isinstance(node.value, astroid.Name)<EOL>and node.value.name == infered.parent.vararg<EOL>):<EOL><INDENT>return<EOL><DEDENT>if isinstance(infered, (astroid.Tuple, astroid.List)):<EOL><INDENT>values = infered.itered()<EOL>if len(targets) != len(values):<EOL><INDENT>if any(isinstance(target, astroid.Starred) for target in targets):<EOL><INDENT>return<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(<EOL>_get_unpacking_extra_info(node, infered),<EOL>len(targets),<EOL>len(values),<EOL>),<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not utils.is_iterable(infered):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(_get_unpacking_extra_info(node, infered),),<EOL>)<EOL><DEDENT><DEDENT>

Check for unbalanced tuple unpacking
        and unpacking non sequences.


def _check_module_attrs(self, node, module, module_names):

assert isinstance(module, astroid.Module), module<EOL>while module_names:<EOL><INDENT>name = module_names.pop(<NUM_LIT:0>)<EOL>if name == "<STR_LIT>":<EOL><INDENT>module = None<EOL>break<EOL><DEDENT>try:<EOL><INDENT>module = next(module.getattr(name)[<NUM_LIT:0>].infer())<EOL>if module is astroid.Uninferable:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>except astroid.NotFoundError:<EOL><INDENT>if module.name in self._ignored_modules:<EOL><INDENT>return None<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>", args=(name, module.name), node=node<EOL>)<EOL>return None<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if module_names:<EOL><INDENT>modname = module.name if module else "<STR_LIT>"<EOL>self.add_message(<EOL>"<STR_LIT>", node=node, args=("<STR_LIT:.>".join(module_names), modname)<EOL>)<EOL>return None<EOL><DEDENT>if isinstance(module, astroid.Module):<EOL><INDENT>return module<EOL><DEDENT>return None<EOL>

check that module_names (list of string) are accessible through the
        given module
        if the latest access name corresponds to a module, return it


consumed = []  <EOL>for child_node in node.get_children():<EOL><INDENT>if isinstance(child_node, astroid.ClassDef):<EOL><INDENT>consumed.extend(self._check_classdef_metaclasses(child_node, node))<EOL><DEDENT><DEDENT>for scope_locals, name in consumed:<EOL><INDENT>scope_locals.pop(name, None)<EOL><DEDENT>

Update consumption analysis for metaclasses.


linter.register_checker(NewStyleConflictChecker(linter))<EOL>

required method to auto register this checker


@check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_functiondef(self, node):<DEDENT>

<EOL>if not node.is_method():<EOL><INDENT>return<EOL><DEDENT>klass = node.parent.frame()<EOL>for stmt in node.nodes_of_class(astroid.Call):<EOL><INDENT>if node_frame_class(stmt) != node_frame_class(node):<EOL><INDENT>continue<EOL><DEDENT>expr = stmt.func<EOL>if not isinstance(expr, astroid.Attribute):<EOL><INDENT>continue<EOL><DEDENT>call = expr.expr<EOL>if not (<EOL>isinstance(call, astroid.Call)<EOL>and isinstance(call.func, astroid.Name)<EOL>and call.func.name == "<STR_LIT>"<EOL>):<EOL><INDENT>continue<EOL><DEDENT>if not klass.newstyle and has_known_bases(klass):<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>if not call.args:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=call)<EOL>continue<EOL><DEDENT><DEDENT>arg0 = call.args[<NUM_LIT:0>]<EOL>if (<EOL>isinstance(arg0, astroid.Call)<EOL>and isinstance(arg0.func, astroid.Name)<EOL>and arg0.func.name == "<STR_LIT:type>"<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=call, args=("<STR_LIT:type>",))<EOL>continue<EOL><DEDENT>if (<EOL>len(call.args) >= <NUM_LIT:2><EOL>and isinstance(call.args[<NUM_LIT:1>], astroid.Name)<EOL>and call.args[<NUM_LIT:1>].name == "<STR_LIT>"<EOL>and isinstance(arg0, astroid.Attribute)<EOL>and arg0.attrname == "<STR_LIT>"<EOL>):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=call, args=("<STR_LIT>",)<EOL>)<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>supcls = call.args and next(call.args[<NUM_LIT:0>].infer(), None)<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT>if klass is not supcls:<EOL><INDENT>name = None<EOL>if supcls:<EOL><INDENT>name = supcls.name<EOL><DEDENT>elif call.args and hasattr(call.args[<NUM_LIT:0>], "<STR_LIT:name>"):<EOL><INDENT>name = call.args[<NUM_LIT:0>].name<EOL><DEDENT>if name:<EOL><INDENT>self.add_message("<STR_LIT>", node=call, args=(name,))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>


path = []<EOL>for is_attribute, specifier in parts:<EOL><INDENT>if is_attribute:<EOL><INDENT>path.append("<STR_LIT>".format(specifier))<EOL><DEDENT>else:<EOL><INDENT>path.append("<STR_LIT>".format(specifier))<EOL><DEDENT><DEDENT>return str(key) + "<STR_LIT>".join(path)<EOL>

Given a list of format specifiers, returns
    the final access path (e.g. a.b.c[0][1]).


linter.register_checker(StringFormatChecker(linter))<EOL>linter.register_checker(StringConstantChecker(linter))<EOL>


if token[<NUM_LIT:0>:<NUM_LIT:2>].lower() in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>token = token[<NUM_LIT:2>:]<EOL><DEDENT>elif token[<NUM_LIT:0>].lower() in ("<STR_LIT:r>", "<STR_LIT:u>", "<STR_LIT:f>"):<EOL><INDENT>token = token[<NUM_LIT:1>:]<EOL><DEDENT>if token[<NUM_LIT:0>:<NUM_LIT:3>] in ('<STR_LIT>', "<STR_LIT>"):<EOL><INDENT>return token[<NUM_LIT:3>:-<NUM_LIT:3>]<EOL><DEDENT>return token[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>

Mostly replicate `ast.literal_eval(token)` manually to avoid any performance hit.
This supports f-strings, contrary to `ast.literal_eval`.
We have to support all string literal notations:
https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals


def _check_new_format(self, node, func):

<EOL>if isinstance(node.func, astroid.Attribute) and not isinstance(<EOL>node.func.expr, astroid.Const<EOL>):<EOL><INDENT>return<EOL><DEDENT>if node.starargs or node.kwargs:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>strnode = next(func.bound.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>if not (isinstance(strnode, astroid.Const) and isinstance(strnode.value, str)):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>call_site = CallSite.from_call(node)<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>fields, num_args, manual_pos = utils.parse_format_method_string(<EOL>strnode.value<EOL>)<EOL><DEDENT>except utils.IncompleteFormatString:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>positional_arguments = call_site.positional_arguments<EOL>named_arguments = call_site.keyword_arguments<EOL>named_fields = {field[<NUM_LIT:0>] for field in fields if isinstance(field[<NUM_LIT:0>], str)}<EOL>if num_args and manual_pos:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>check_args = False<EOL>num_args += sum(<NUM_LIT:1> for field in named_fields if field == "<STR_LIT>")<EOL>if named_fields:<EOL><INDENT>for field in named_fields:<EOL><INDENT>if field and field not in named_arguments:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(field,)<EOL>)<EOL><DEDENT><DEDENT>for field in named_arguments:<EOL><INDENT>if field not in named_fields:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(field,)<EOL>)<EOL><DEDENT><DEDENT>num_args = num_args or manual_pos<EOL>if positional_arguments or num_args:<EOL><INDENT>empty = any(True for field in named_fields if field == "<STR_LIT>")<EOL>if named_arguments or empty:<EOL><INDENT>check_args = True<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>check_args = True<EOL><DEDENT>if check_args:<EOL><INDENT>num_args = num_args or manual_pos<EOL>if len(positional_arguments) > num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif len(positional_arguments) < num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>self._detect_vacuous_formatting(node, positional_arguments)<EOL>self._check_new_format_specifiers(node, fields, named_arguments)<EOL>


def _check_new_format_specifiers(self, node, fields, named):

for key, specifiers in fields:<EOL><INDENT>if key == "<STR_LIT>":<EOL><INDENT>key = <NUM_LIT:0><EOL><DEDENT>if isinstance(key, numbers.Number):<EOL><INDENT>try:<EOL><INDENT>argname = utils.get_argument_from_call(node, key)<EOL><DEDENT>except utils.NoSuchArgumentError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if key not in named:<EOL><INDENT>continue<EOL><DEDENT>argname = named[key]<EOL><DEDENT>if argname in (astroid.Uninferable, None):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>argument = next(argname.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT>if not specifiers or argument is astroid.Uninferable:<EOL><INDENT>continue<EOL><DEDENT>if argument.parent and isinstance(argument.parent, astroid.Arguments):<EOL><INDENT>continue<EOL><DEDENT>previous = argument<EOL>parsed = []<EOL>for is_attribute, specifier in specifiers:<EOL><INDENT>if previous is astroid.Uninferable:<EOL><INDENT>break<EOL><DEDENT>parsed.append((is_attribute, specifier))<EOL>if is_attribute:<EOL><INDENT>try:<EOL><INDENT>previous = previous.getattr(specifier)[<NUM_LIT:0>]<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>if (<EOL>hasattr(previous, "<STR_LIT>")<EOL>and previous.has_dynamic_getattr()<EOL>):<EOL><INDENT>break<EOL><DEDENT>path = get_access_path(key, parsed)<EOL>self.add_message(<EOL>"<STR_LIT>",<EOL>args=(specifier, path),<EOL>node=node,<EOL>)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warn_error = False<EOL>if hasattr(previous, "<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>previous = previous.getitem(astroid.Const(specifier))<EOL><DEDENT>except (<EOL>astroid.AstroidIndexError,<EOL>astroid.AstroidTypeError,<EOL>astroid.AttributeInferenceError,<EOL>):<EOL><INDENT>warn_error = True<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>break<EOL><DEDENT>if previous is astroid.Uninferable:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>previous.getattr("<STR_LIT>")<EOL>break<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>warn_error = True<EOL><DEDENT><DEDENT>if warn_error:<EOL><INDENT>path = get_access_path(key, parsed)<EOL>self.add_message(<EOL>"<STR_LIT>", args=(specifier, path), node=node<EOL>)<EOL>break<EOL><DEDENT><DEDENT>try:<EOL><INDENT>previous = next(previous.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>

Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").


def process_non_raw_string_token(self, prefix, string_body, start_row):

<EOL>i = <NUM_LIT:0><EOL>while True:<EOL><INDENT>i = string_body.find("<STR_LIT:\\>", i)<EOL>if i == -<NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT>next_char = string_body[i + <NUM_LIT:1>]<EOL>match = string_body[i : i + <NUM_LIT:2>]<EOL>if next_char in self.UNICODE_ESCAPE_CHARACTERS:<EOL><INDENT>if "<STR_LIT:u>" in prefix:<EOL><INDENT>pass<EOL><DEDENT>elif (_PY3K or self._unicode_literals) and "<STR_LIT:b>" not in prefix:<EOL><INDENT>pass  <EOL><DEDENT>else:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>line=start_row,<EOL>args=(match,),<EOL>)<EOL><DEDENT><DEDENT>elif next_char not in self.ESCAPE_CHARACTERS:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", line=start_row, args=(match,)<EOL>)<EOL><DEDENT>i += <NUM_LIT:2><EOL><DEDENT>

check for bad escapes in a non-raw string.

        prefix: lowercase string of eg 'ur' string prefix markers.
        string_body: the un-parsed body of the string, not including the quote
        marks.
        start_row: integer line number in the source.


current = node<EOL>while current and not isinstance(current.parent, astroid.ExceptHandler):<EOL><INDENT>current = current.parent<EOL><DEDENT>if not current or not utils.error_of_type(current.parent, ImportError):<EOL><INDENT>return False<EOL><DEDENT>try_block = current.parent.parent<EOL>for import_node in try_block.nodes_of_class((astroid.ImportFrom, astroid.Import)):<EOL><INDENT>for name, alias in import_node.names:<EOL><INDENT>if alias:<EOL><INDENT>if alias == node.name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif name == node.name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Detect that the given node (AssignName) is inside an
    exception handler and redefines an import from the tryexcept body.
    Returns True if the node redefines an import, False otherwise.


parent = node.parent<EOL>while parent is not None:<EOL><INDENT>if isinstance(<EOL>parent,<EOL>(<EOL>astroid.For,<EOL>astroid.ListComp,<EOL>astroid.SetComp,<EOL>astroid.DictComp,<EOL>astroid.GeneratorExp,<EOL>),<EOL>):<EOL><INDENT>return True<EOL><DEDENT>parent = parent.parent<EOL><DEDENT>return False<EOL>

return True if the node is inside a kind of for loop


for elmt in nested_list:<EOL><INDENT>if isinstance(elmt, (list, tuple)):<EOL><INDENT>if in_nested_list(elmt, obj):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif elmt == obj:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

return true if the object is an element of <nested_list> or of a nested
    list


loop_nodes = (astroid.For, astroid.While)<EOL>parent = break_node.parent<EOL>while not isinstance(parent, loop_nodes) or break_node in getattr(<EOL>parent, "<STR_LIT>", []<EOL>):<EOL><INDENT>break_node = parent<EOL>parent = parent.parent<EOL>if parent is None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return parent<EOL>

Returns the loop node that holds the break node in arguments.

Args:
    break_node (astroid.Break): the break node of interest.

Returns:
    astroid.For or astroid.While: the loop node holding the break node.


loop_nodes = (astroid.For, astroid.While)<EOL>definition_nodes = (astroid.FunctionDef, astroid.ClassDef)<EOL>inner_loop_nodes = [<EOL>_node<EOL>for _node in loop.nodes_of_class(loop_nodes, skip_klass=definition_nodes)<EOL>if _node != loop<EOL>]<EOL>return any(<EOL>_node<EOL>for _node in loop.nodes_of_class(astroid.Break, skip_klass=definition_nodes)<EOL>if _get_break_loop_node(_node) not in inner_loop_nodes<EOL>)<EOL>

Returns true if a loop may ends up in a break statement.

Args:
    loop (astroid.For, astroid.While): the loop node inspected.

Returns:
    bool: True if the loop may ends up in a break statement, False otherwise.


property_classes = {BUILTIN_PROPERTY}<EOL>property_names = set()  <EOL>if config is not None:<EOL><INDENT>property_classes.update(config.property_classes)<EOL>property_names.update(<EOL>(prop.rsplit("<STR_LIT:.>", <NUM_LIT:1>)[-<NUM_LIT:1>] for prop in config.property_classes)<EOL>)<EOL><DEDENT>return property_classes, property_names<EOL>

Returns a tuple of property classes and names.

    Property classes are fully qualified, such as 'abc.abstractproperty' and
    property names are the actual names, such as 'abstract_property'.


property_classes, property_names = _get_properties(config)<EOL>if not node.is_method():<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if node.decorators:<EOL><INDENT>decorators = node.decorators.nodes<EOL><DEDENT>else:<EOL><INDENT>decorators = []<EOL><DEDENT>for decorator in decorators:<EOL><INDENT>if isinstance(decorator, astroid.Name) or (<EOL>isinstance(decorator, astroid.Attribute)<EOL>and decorator.attrname in property_names<EOL>):<EOL><INDENT>infered = utils.safe_infer(decorator)<EOL>if infered and infered.qname() in property_classes:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>elif isinstance(decorator, astroid.Attribute) and decorator.attrname in (<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Determine the name type whose regex the a function's name should match.

    :param node: A function node.
    :type node: astroid.node_classes.NodeNG
    :param config: Configuration from which to pull additional property classes.
    :type config: :class:`optparse.Values`

    :returns: One of ('function', 'method', 'attr')
    :rtype: str


return len(utils.unimplemented_abstract_methods(node)) > <NUM_LIT:0><EOL>

Determine if the given `node` has abstract methods.

The methods should be made abstract by decorating them
with `abc` decorators.


def report_by_type_stats(sect, stats, _):

<EOL>nice_stats = {}<EOL>for node_type in ("<STR_LIT>", "<STR_LIT:class>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>total = stats[node_type]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>nice_stats[node_type] = {}<EOL>if total != <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>documented = total - stats["<STR_LIT>" + node_type]<EOL>percent = (documented * <NUM_LIT>) / total<EOL>nice_stats[node_type]["<STR_LIT>"] = "<STR_LIT>" % percent<EOL><DEDENT>except KeyError:<EOL><INDENT>nice_stats[node_type]["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>percent = (stats["<STR_LIT>" + node_type] * <NUM_LIT>) / total<EOL>nice_stats[node_type]["<STR_LIT>"] = "<STR_LIT>" % percent<EOL><DEDENT>except KeyError:<EOL><INDENT>nice_stats[node_type]["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>lines = ("<STR_LIT:type>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>for node_type in ("<STR_LIT>", "<STR_LIT:class>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>new = stats[node_type]<EOL>lines += (<EOL>node_type,<EOL>str(new),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>nice_stats[node_type].get("<STR_LIT>", "<STR_LIT:0>"),<EOL>nice_stats[node_type].get("<STR_LIT>", "<STR_LIT:0>"),<EOL>)<EOL><DEDENT>sect.append(reporter_nodes.Table(children=lines, cols=<NUM_LIT:6>, rheaders=<NUM_LIT:1>))<EOL>

make a report of

    * percentage of different types documented
    * percentage of different types with a bad name


if node.decorators:<EOL><INDENT>for decorator in node.decorators.nodes:<EOL><INDENT>if (<EOL>isinstance(decorator, astroid.Attribute)<EOL>and getattr(decorator.expr, "<STR_LIT:name>", None) == node.name<EOL>):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

return True if the object is a method redefined via decorator.

    For example:
        @property
        def x(self): return self._x
        @x.setter
        def x(self, value): self._x = value


return isinstance(call, astroid.Call) and len(call.args) == <NUM_LIT:1> and not call.keywords<EOL>

Is this a call with exactly 1 argument,
    where that argument is positional?


if isinstance(node.parent, astroid.Call):<EOL><INDENT>return<EOL><DEDENT>if PY35 and isinstance(<EOL>node.parent, (astroid.List, astroid.Tuple, astroid.Set, astroid.Dict)<EOL>):<EOL><INDENT>return<EOL><DEDENT>stmt = node.statement()<EOL>if not isinstance(stmt, astroid.Assign):<EOL><INDENT>return<EOL><DEDENT>if stmt.value is node or stmt.value.parent_of(node):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Check that a Starred expression is used in an assignment target.


def same_scope(current):<EOL><INDENT>return current.scope() is node<EOL><DEDENT>from_iter = itertools.chain.from_iterable<EOL>nonlocals = set(<EOL>from_iter(<EOL>child.names<EOL>for child in node.nodes_of_class(astroid.Nonlocal)<EOL>if same_scope(child)<EOL>)<EOL>)<EOL>if not nonlocals:<EOL><INDENT>return<EOL><DEDENT>global_vars = set(<EOL>from_iter(<EOL>child.names<EOL>for child in node.nodes_of_class(astroid.Global)<EOL>if same_scope(child)<EOL>)<EOL>)<EOL>for name in nonlocals.intersection(global_vars):<EOL><INDENT>self.add_message("<STR_LIT>", args=(name,), node=node)<EOL><DEDENT>

Check that a name is both nonlocal and global.


if (<EOL>(node.op in "<STR_LIT>")<EOL>and isinstance(node.operand, astroid.UnaryOp)<EOL>and (node.operand.op == node.op)<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=node.op * <NUM_LIT:2>)<EOL><DEDENT>

check use of the non-existent ++ and -- operator operator


try:<EOL><INDENT>for inferred in node.func.infer():<EOL><INDENT>self._check_inferred_class_is_abstract(inferred, node)<EOL><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>

Check instantiating abstract class with
        abc.ABCMeta as metaclass.


if node.orelse and not _loop_exits_early(node):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>line=node.orelse[<NUM_LIT:0>].lineno - <NUM_LIT:1>,<EOL>)<EOL><DEDENT>

Check that any loop with an else clause has a break statement.


def _check_in_loop(self, node, node_name):

_node = node.parent<EOL>while _node:<EOL><INDENT>if isinstance(_node, (astroid.For, astroid.While)):<EOL><INDENT>if node not in _node.orelse:<EOL><INDENT>return<EOL><DEDENT><DEDENT>if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)):<EOL><INDENT>break<EOL><DEDENT>if (<EOL>isinstance(_node, astroid.TryFinally)<EOL>and node in _node.finalbody<EOL>and isinstance(node, astroid.Continue)<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>_node = _node.parent<EOL><DEDENT>self.add_message("<STR_LIT>", node=node, args=node_name)<EOL>

check that a node is inside a for or while loop


def _check_redefinition(self, redeftype, node):

parent_frame = node.parent.frame()<EOL>defined_self = parent_frame[node.name]<EOL>if defined_self is not node and not astroid.are_exclusive(node, defined_self):<EOL><INDENT>if (<EOL>isinstance(parent_frame, astroid.ClassDef)<EOL>and node.name in REDEFINABLE_METHODS<EOL>):<EOL><INDENT>return<EOL><DEDENT>dummy_variables_rgx = lint_utils.get_global_option(<EOL>self, "<STR_LIT>", default=None<EOL>)<EOL>if dummy_variables_rgx and dummy_variables_rgx.match(node.name):<EOL><INDENT>return<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(redeftype, defined_self.fromlineno),<EOL>)<EOL><DEDENT>

check for redefinition of a function / method / class name


self._tryfinallys = []<EOL>self.stats = self.linter.add_stats(module=<NUM_LIT:0>, function=<NUM_LIT:0>, method=<NUM_LIT:0>, class_=<NUM_LIT:0>)<EOL>

initialize visit variables and statistics


self.stats["<STR_LIT>"] += <NUM_LIT:1><EOL>

check module name, docstring and required arguments


self.stats["<STR_LIT:class>"] += <NUM_LIT:1><EOL>

check module name, docstring and redefinition
        increment branch counter


@utils.check_messages(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"<EOL>)<EOL><INDENT>def visit_expr(self, node):<DEDENT>

expr = node.value<EOL>if isinstance(expr, astroid.Const) and isinstance(expr.value, str):<EOL><INDENT>scope = expr.scope()<EOL>if isinstance(<EOL>scope, (astroid.ClassDef, astroid.Module, astroid.FunctionDef)<EOL>):<EOL><INDENT>if isinstance(scope, astroid.FunctionDef) and scope.name != "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>sibling = expr.previous_sibling()<EOL>if (<EOL>sibling is not None<EOL>and sibling.scope() is scope<EOL>and isinstance(sibling, (astroid.Assign, astroid.AnnAssign))<EOL>):<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>if isinstance(<EOL>expr, (astroid.Yield, astroid.Await, astroid.Ellipsis, astroid.Call)<EOL>) or (<EOL>isinstance(node.parent, astroid.TryExcept) and node.parent.body == [node]<EOL>):<EOL><INDENT>return<EOL><DEDENT>if any(expr.nodes_of_class(astroid.Call)):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=expr.as_string()<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

check for various kind of statements without effect


<EOL>if node.args.defaults:<EOL><INDENT>return<EOL><DEDENT>call = node.body<EOL>if not isinstance(call, astroid.Call):<EOL><INDENT>return<EOL><DEDENT>if isinstance(node.body.func, astroid.Attribute) and isinstance(<EOL>node.body.func.expr, astroid.Call<EOL>):<EOL><INDENT>return<EOL><DEDENT>call_site = CallSite.from_call(call)<EOL>ordinary_args = list(node.args.args)<EOL>new_call_args = list(self._filter_vararg(node, call.args))<EOL>if node.args.kwarg:<EOL><INDENT>if self._has_variadic_argument(call.kwargs, node.args.kwarg):<EOL><INDENT>return<EOL><DEDENT><DEDENT>if node.args.vararg:<EOL><INDENT>if self._has_variadic_argument(call.starargs, node.args.vararg):<EOL><INDENT>return<EOL><DEDENT><DEDENT>elif call.starargs:<EOL><INDENT>return<EOL><DEDENT>if call.keywords:<EOL><INDENT>lambda_kwargs = {keyword.name for keyword in node.args.defaults}<EOL>if len(lambda_kwargs) != len(call_site.keyword_arguments):<EOL><INDENT>return<EOL><DEDENT>if set(call_site.keyword_arguments).difference(lambda_kwargs):<EOL><INDENT>return<EOL><DEDENT><DEDENT>if len(ordinary_args) != len(new_call_args):<EOL><INDENT>return<EOL><DEDENT>for arg, passed_arg in zip(ordinary_args, new_call_args):<EOL><INDENT>if not isinstance(passed_arg, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>if arg.name != passed_arg.name:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.add_message("<STR_LIT>", line=node.fromlineno, node=node)<EOL>

check whether or not the lambda is suspicious


self.stats[node.is_method() and "<STR_LIT>" or "<STR_LIT>"] += <NUM_LIT:1><EOL>self._check_dangerous_default(node)<EOL>

check function name, docstring, arguments, redefinition,
        variable names, max locals


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_return(self, node):<DEDENT>

self._check_unreachable(node)<EOL>self._check_not_in_finally(node, "<STR_LIT>", (astroid.FunctionDef,))<EOL>

1 - check is the node has a right sibling (if so, that's some
        unreachable code)
        2 - check is the node is inside the finally clause of a try...finally
        block


check is the node has a right sibling (if so, that's some unreachable
        code)


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_break(self, node):<DEDENT>

<EOL>self._check_unreachable(node)<EOL>self._check_not_in_finally(node, "<STR_LIT>", (astroid.For, astroid.While))<EOL>


check if the node has a right sibling (if so, that's some unreachable
        code)


self.add_message("<STR_LIT>", node=node)<EOL>


@utils.check_messages(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"<EOL>)<EOL><INDENT>def visit_call(self, node):<DEDENT>

self._check_misplaced_format_function(node)<EOL>if isinstance(node.func, astroid.Name):<EOL><INDENT>name = node.func.name<EOL>if not (name in node.frame() or name in node.root()):<EOL><INDENT>if name == "<STR_LIT>":<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>self._check_reversed(node)<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT><DEDENT>

visit a Call node -> check if this is not a blacklisted builtin
        call and check for * or ** use


if (<EOL>node.fail is None<EOL>and isinstance(node.test, astroid.Tuple)<EOL>and len(node.test.elts) == <NUM_LIT:2><EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

check the use of an assert statement on a tuple.


keys = set()<EOL>for k, _ in node.items:<EOL><INDENT>if isinstance(k, astroid.Const):<EOL><INDENT>key = k.value<EOL>if key in keys:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=key)<EOL><DEDENT>keys.add(key)<EOL><DEDENT><DEDENT>


unreach_stmt = node.next_sibling()<EOL>if unreach_stmt is not None:<EOL><INDENT>self.add_message("<STR_LIT>", node=unreach_stmt)<EOL><DEDENT>


def _check_not_in_finally(self, node, node_name, breaker_classes=()):

<EOL>if not self._tryfinallys:<EOL><INDENT>return<EOL><DEDENT>_parent = node.parent<EOL>_node = node<EOL>while _parent and not isinstance(_parent, breaker_classes):<EOL><INDENT>if hasattr(_parent, "<STR_LIT>") and _node in _parent.finalbody:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=node_name)<EOL>return<EOL><DEDENT>_node = _parent<EOL>_parent = _node.parent<EOL><DEDENT>

check that a node is not inside a finally clause of a
        try...finally statement.
        If we found before a try...finally bloc a parent which its type is
        in breaker_classes, we skip the whole check.


try:<EOL><INDENT>argument = utils.safe_infer(utils.get_argument_from_call(node, position=<NUM_LIT:0>))<EOL><DEDENT>except utils.NoSuchArgumentError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if argument is astroid.Uninferable:<EOL><INDENT>return<EOL><DEDENT>if argument is None:<EOL><INDENT>if isinstance(node.args[<NUM_LIT:0>], astroid.Call):<EOL><INDENT>try:<EOL><INDENT>func = next(node.args[<NUM_LIT:0>].func.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>if getattr(<EOL>func, "<STR_LIT:name>", None<EOL>) == "<STR_LIT>" and utils.is_builtin_object(func):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>if isinstance(argument, (astroid.List, astroid.Tuple)):<EOL><INDENT>return<EOL><DEDENT>if isinstance(argument, astroid.Instance):<EOL><INDENT>if argument._proxied.name == "<STR_LIT>" and utils.is_builtin_object(<EOL>argument._proxied<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>if any(<EOL>ancestor.name == "<STR_LIT>" and utils.is_builtin_object(ancestor)<EOL>for ancestor in argument._proxied.ancestors()<EOL>):<EOL><INDENT>try:<EOL><INDENT>argument.locals[REVERSED_PROTOCOL_METHOD]<EOL><DEDENT>except KeyError:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>return<EOL><DEDENT><DEDENT>if hasattr(argument, "<STR_LIT>"):<EOL><INDENT>for methods in REVERSED_METHODS:<EOL><INDENT>for meth in methods:<EOL><INDENT>try:<EOL><INDENT>argument.getattr(meth)<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>

check that the argument to `reversed` is a sequence