Search is not available for this dataset
text
stringlengths
75
104k
def visit_project(self, node): """visit a pyreverse.utils.Project node * optionally tag the node with a unique id """ if self.tag: node.uid = self.generate_id() for module in node.modules: self.visit(module)
def visit_package(self, node): """visit an astroid.Package node * optionally tag the node with a unique id """ if self.tag: node.uid = self.generate_id() for subelmt in node.values(): self.visit(subelmt)
def visit_module(self, node): """visit an astroid.Module node * set the locals_type mapping * set the depends mapping * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return node.locals_type = collections.defaultdict(...
def visit_classdef(self, node): """visit an astroid.Class node * set the locals_type and instance_attrs_type mappings * set the implements list and build it * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return node...
def visit_functiondef(self, node): """visit an astroid.Function node * set the locals_type mapping * optionally tag the node with a unique id """ if hasattr(node, "locals_type"): return node.locals_type = collections.defaultdict(list) if self.tag: ...
def visit_assignname(self, node): """visit an astroid.AssignName node handle locals_type """ # avoid double parsing done by different Linkers.visit # running over the same project: if hasattr(node, "_handled"): return node._handled = True if n...
def handle_assignattr_type(node, parent): """handle an astroid.assignattr node handle instance_attrs_type """ try: values = set(node.infer()) current = set(parent.instance_attrs_type[node.attrname]) parent.instance_attrs_type[node.attrname] = list(cur...
def visit_import(self, node): """visit an astroid.Import node resolve module dependencies """ context_file = node.root().file for name in node.names: relative = modutils.is_relative(name[0], context_file) self._imported_module(node, name[0], relative)
def visit_importfrom(self, node): """visit an astroid.ImportFrom node resolve module dependencies """ basename = node.modname context_file = node.root().file if context_file is not None: relative = modutils.is_relative(basename, context_file) else: ...
def compute_module(self, context_name, mod_path): """return true if the module should be added to dependencies""" package_dir = os.path.dirname(self.project.path) if context_name == mod_path: return 0 if modutils.is_standard_module(mod_path, (package_dir,)): retur...
def _imported_module(self, node, mod_path, relative): """Notify an imported module, used to analyze dependencies""" module = node.root() context_name = module.name if relative: mod_path = "%s.%s" % (".".join(context_name.split(".")[:-1]), mod_path) if self.compute_mod...
def implements(obj, interface): """Return true if the give object (maybe an instance or class) implements the interface. """ kimplements = getattr(obj, "__implements__", ()) if not isinstance(kimplements, (list, tuple)): kimplements = (kimplements,) for implementedinterface in kimplement...
def _get_ansi_code(color=None, style=None): """return ansi escape code corresponding to color and style :type color: str or None :param color: the color name (see `ANSI_COLORS` for available values) or the color number when 256 colors are available :type style: str or None :param style...
def colorize_ansi(msg, color=None, style=None): """colorize message by wrapping it with ansi escape codes :type msg: str or unicode :param msg: the message string to colorize :type color: str or None :param color: the color identifier (see `ANSI_COLORS` for available values) :type style...
def register(linter): """Register the reporter classes with the linter.""" linter.register_reporter(TextReporter) linter.register_reporter(ParseableTextReporter) linter.register_reporter(VSTextReporter) linter.register_reporter(ColorizedTextReporter)
def handle_message(self, msg): """manage message of different type and in the context of path""" if msg.module not in self._modules: if msg.module: self.writeln("************* Module %s" % msg.module) self._modules.add(msg.module) else: ...
def _display(self, layout): """launch layouts display""" print(file=self.out) TextWriter().format(layout, self.out)
def handle_message(self, msg): """manage message of different types, and colorize output using ansi escape codes """ if msg.module not in self._modules: color, style = self._get_decoration("S") if msg.module: modsep = colorize_ansi( ...
def open_graph(self, **args): """open a vcg graph """ self._stream.write("%sgraph:{\n" % self._indent) self._inc_indent() self._write_attributes(GRAPH_ATTRS, **args)
def node(self, title, **args): """draw a node """ self._stream.write('%snode: {title:"%s"' % (self._indent, title)) self._write_attributes(NODE_ATTRS, **args) self._stream.write("}\n")
def edge(self, from_node, to_node, edge_type="", **args): """draw an edge from a node to another. """ self._stream.write( '%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node) ) self._write_attributes(EDGE_ATTRS, **ar...
def _write_attributes(self, attributes_dict, **args): """write graph, node or edge attributes """ for key, value in args.items(): try: _type = attributes_dict[key] except KeyError: raise Exception( """no such attribute %...
def get_access_path(key, parts): """ Given a list of format specifiers, returns the final access path (e.g. a.b.c[0][1]). """ path = [] for is_attribute, specifier in parts: if is_attribute: path.append(".{}".format(specifier)) else: path.append("[{!r}]".forma...
def register(linter): """required method to auto register this checker """ linter.register_checker(StringFormatChecker(linter)) linter.register_checker(StringConstantChecker(linter))
def str_eval(token): """ 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): """ Check the new string formatting. """ # TODO: skip (for now) format nodes which don't have # an explicit string on the left side of the format operation. # We do this because our inference engine can't properly handle # ...
def _check_new_format_specifiers(self, node, fields, named): """ Check attribute and index access in the format string ("{0.a}" and "{0[a]}"). """ for key, specifiers in fields: # Obtain the argument. If it can't be obtained # or infered, skip this check. ...
def process_non_raw_string_token(self, prefix, string_body, start_row): """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 ...
def visit_section(self, layout): """display a section as text """ self.section += 1 self.writeln() self.format_children(layout) self.section -= 1 self.writeln()
def visit_evaluationsection(self, layout): """Display an evaluation section as a text.""" self.section += 1 self.format_children(layout) self.section -= 1 self.writeln()
def visit_table(self, layout): """display a table as text""" table_content = self.get_table_content(layout) # get columns width cols_width = [0] * len(table_content[0]) for row in table_content: for index, col in enumerate(row): cols_width[index] = max...
def default_table(self, layout, table_content, cols_width): """format a table""" cols_width = [size + 1 for size in cols_width] format_strings = " ".join(["%%-%ss"] * len(cols_width)) format_strings = format_strings % tuple(cols_width) format_strings = format_strings.split(" ") ...
def visit_verbatimtext(self, layout): """display a verbatim layout as text (so difficult ;) """ self.writeln("::\n") for line in layout.data.splitlines(): self.writeln(" " + line) self.writeln()
def add_renamed_message(self, old_id, old_symbol, new_symbol): """Register the old ID and symbol for a warning that was renamed. This allows users to keep using the old ID/symbol in suppressions. """ message_definition = self.get_message_definitions(new_symbol)[0] message_defini...
def register_messages_from_checker(self, checker): """Register all messages from a checker. :param BaseChecker checker: """ checker.check_consistency() for message in checker.messages: self.register_message(message)
def register_message(self, message): """Register a MessageDefinition with consistency in mind. :param MessageDefinition message: The message definition being added. """ self._check_id_and_symbol_consistency(message.msgid, message.symbol) self._check_symbol(message.msgid, message...
def _register_alternative_name(self, msg, msgid, symbol): """helper for register_message()""" self._check_id_and_symbol_consistency(msgid, symbol) self._alternative_names[msgid] = msg self._alternative_names[symbol] = msg
def _check_symbol(self, msgid, symbol): """Check that a symbol is not already used. """ other_message = self._messages_definitions.get(symbol) if other_message: self._raise_duplicate_msg_id(symbol, msgid, other_message.msgid) else: alternative_msgid = None ...
def _raise_duplicate_symbol(msgid, symbol, other_symbol): """Raise an error when a symbol is duplicated. :param str msgid: The msgid corresponding to the symbols :param str symbol: Offending symbol :param str other_symbol: Other offending symbol :raises InvalidMessageError: when...
def _raise_duplicate_msg_id(symbol, msgid, other_msgid): """Raise an error when a msgid is duplicated. :param str symbol: The symbol corresponding to the msgids :param str msgid: Offending msgid :param str other_msgid: Other offending msgid :raises InvalidMessageError: when a ms...
def get_message_definitions(self, msgid_or_symbol: str) -> list: """Returns the Message object for this message. :param str msgid_or_symbol: msgid_or_symbol may be either a numeric or symbolic id. :raises UnknownMessageError: if the message id is not defined. :rtype: List of MessageDefi...
def get_msg_display_string(self, msgid): """Generates a user-consumable representation of a message. Can be just the message ID or the ID and the symbol. """ message_definitions = self.get_message_definitions(msgid) if len(message_definitions) == 1: return repr(messa...
def help_message(self, msgids): """Display help messages for the given message identifiers""" for msgid in msgids: try: for message_definition in self.get_message_definitions(msgid): print(message_definition.format_help(checkerref=True)) ...
def list_messages(self): """Output full messages list documentation in ReST format. """ messages = sorted(self._messages_definitions.values(), key=lambda m: m.msgid) for message in messages: if not message.may_be_emitted(): continue print(message.format_he...
def register(linter): """Required method to auto register this checker. :param linter: Main interface object for Pylint plugins :type linter: Pylint object """ warnings.warn( "This plugin is deprecated, use pylint.extensions.docparams instead.", DeprecationWarning, ) linter....
def builder_inited(app): """Output full documentation in ReST format for all extension modules""" # PACKAGE/docs/exts/pylint_extensions.py --> PACKAGE/ base_path = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ) # PACKAGE/ --> PACKAGE/pylint/extensions ext_...
def run_pylint(): """run pylint""" from pylint.lint import Run try: Run(sys.argv[1:]) except KeyboardInterrupt: sys.exit(1)
def _cpu_count() -> int: """Use sched_affinity if available for virtualized or containerized environments.""" sched_getaffinity = getattr(os, "sched_getaffinity", None) # pylint: disable=not-callable,using-constant-test if sched_getaffinity: return len(sched_getaffinity(0)) if multiprocessin...
def report_total_messages_stats(sect, stats, previous_stats): """make total errors / warnings report""" lines = ["type", "number", "previous", "difference"] lines += checkers.table_lines_from_stats( stats, previous_stats, ("convention", "refactor", "warning", "error") ) sect.append(report_no...
def report_messages_stats(sect, stats, _): """make messages type report""" if not stats["by_msg"]: # don't print this report when we didn't detected any errors raise exceptions.EmptyReportError() in_order = sorted( [ (value, msg_id) for msg_id, value in stats[...
def report_messages_by_module_stats(sect, stats, _): """make errors / warnings by modules report""" if len(stats["by_module"]) == 1: # don't print this report when we are analysing a single module raise exceptions.EmptyReportError() by_mod = collections.defaultdict(dict) for m_type in ("...
def preprocess_options(args, search_for): """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 """ i = 0 while i < len(args): arg = args[i] if arg.startswith("-...
def fix_import_path(args): """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 v...
def load_plugin_modules(self, modnames): """take a list of module names which are pylint plugins and load and register them """ for modname in modnames: if modname in self._dynamic_plugins: continue self._dynamic_plugins.add(modname) mo...
def load_plugin_configuration(self): """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. """ for modname in self._dynamic_plugins...
def set_option(self, optname, value, action=None, optdict=None): """overridden from config.OptionsProviderMixin to handle some special options """ if optname in self._options_methods or optname in self._bw_options_methods: if value: try: me...
def register_checker(self, checker): """register a new checker checker is an object implementing IRawChecker or / and IAstroidChecker """ assert checker.priority <= 0, "checker priority can't be >= 0" self._checkers[checker.name].append(checker) for r_id, r_title, r_cb i...
def disable_reporters(self): """disable all reporters""" for _reporters in self._reports.values(): for report_id, _, _ in _reporters: self.disable_report(report_id)
def error_mode(self): """error mode: enable only errors; no reports, no persistent""" self._error_mode = True self.disable_noerror_messages() self.disable("miscellaneous") if self._python3_porting_mode: self.disable("all") for msg_id in self._checker_messa...
def python3_porting_mode(self): """Disable all other checkers and enable Python 3 warnings.""" self.disable("all") self.enable("python3") if self._error_mode: # The error mode was activated, using the -E flag. # So we'll need to enable only the errors from the ...
def process_tokens(self, tokens): """process tokens from the current module to search for module/block level options """ control_pragmas = {"disable", "enable"} for (tok_type, content, start, _, _) in tokens: if tok_type != tokenize.COMMENT: continue ...
def get_checkers(self): """return all available checkers as a list""" return [self] + [ c for _checkers in self._checkers.values() for c in _checkers if c is not self ]
def get_checker_names(self): """Get all the checker names that this linter knows about.""" current_checkers = self.get_checkers() return sorted( {check.name for check in current_checkers if check.name != "master"} )
def prepare_checkers(self): """return checkers needed for activated messages and reports""" if not self.config.reports: self.disable_reporters() # get needed checkers neededcheckers = [self] for checker in self.get_checkers()[1:]: messages = {msg for msg i...
def check(self, files_or_modules): """main checking entry: check a list of files or modules from their name. """ # initialize msgs_state now that all messages have been registered into # the store for msg in self.msgs_store.messages: if not msg.may_be_emitted(...
def expand_files(self, modules): """get modules and errors from a list of modules and handle errors """ result, errors = utils.expand_modules( modules, self.config.black_list, self.config.black_list_re ) for error in errors: message = modname = error["mod"...
def set_current_module(self, modname, filepath=None): """set the name of the currently analyzed module and init statistics for it """ if not modname and filepath is None: return self.reporter.on_set_current_module(modname, filepath) self.current_name = modname...
def get_ast(self, filepath, modname): """return an ast(roid) representation for a module""" try: return MANAGER.ast_from_file(filepath, modname, source=True) except astroid.AstroidSyntaxError as ex: # pylint: disable=no-member self.add_message( ...
def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers): """Check a module from its astroid representation.""" try: tokens = utils.tokenize_module(ast_node) except tokenize.TokenError as ex: self.add_message("syntax-error", line=ex.args[1][0], args=ex...
def open(self): """initialize counters""" self.stats = {"by_module": {}, "by_msg": {}} MANAGER.always_load_extensions = self.config.unsafe_load_any_extension MANAGER.max_inferable_values = self.config.limit_inference_results MANAGER.extension_package_whitelist.update(self.config....
def generate_reports(self): """close the whole package /module, it's time to make reports ! if persistent run, pickle results for later comparison """ # Display whatever messages are left on the reporter. self.reporter.display_messages(report_nodes.Section()) if self.fi...
def _report_evaluation(self): """make the global evaluation report""" # check with at least check 1 statements (usually 0 when there is a # syntax error preventing pylint from further processing) previous_stats = config.load_results(self.file_state.base_name) if self.stats["state...
def cb_add_plugins(self, name, value): """callback for option preprocessing (i.e. before option parsing)""" self._plugins.extend(utils._splitstrip(value))
def cb_generate_config(self, *args, **kwargs): """optik callback for sample config file generation""" self.linter.generate_config(skipsections=("COMMANDS",)) sys.exit(0)
def cb_generate_manpage(self, *args, **kwargs): """optik callback for sample config file generation""" from pylint import __pkginfo__ self.linter.generate_manpage(__pkginfo__) sys.exit(0)
def cb_help_message(self, option, optname, value, parser): """optik callback for printing some help about a particular message""" self.linter.msgs_store.help_message(utils._splitstrip(value)) sys.exit(0)
def cb_full_documentation(self, option, optname, value, parser): """optik callback for printing full documentation""" self.linter.print_full_documentation() sys.exit(0)
def cb_list_messages(self, option, optname, value, parser): # FIXME """optik callback for printing available messages""" self.linter.msgs_store.list_messages() sys.exit(0)
def cb_list_groups(self, *args, **kwargs): """List all the check groups that pylint knows about These should be useful to know what check groups someone can disable or enable. """ for check in self.linter.get_checker_names(): print(check) sys.exit(0)
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
def get_module_and_frameid(node): """return the module name and the frame id in the module""" frame = node.frame() module, obj = "", [] while frame: if isinstance(frame, Module): module = frame.name else: obj.append(getattr(frame, "name", "<lambda>")) try:...
def safe_decode(line, encoding, *args, **kwargs): """return decoded line from encoding or decode with default encoding""" try: return line.decode(encoding or sys.getdefaultencoding(), *args, **kwargs) except LookupError: return line.decode(sys.getdefaultencoding(), *args, **kwargs)
def _basename_in_blacklist_re(base_name, black_list_re): """Determines if the basename is matched in a regex blacklist :param str base_name: The basename of the file :param list black_list_re: A collection of regex patterns to match against. Successful matches are blacklisted. :returns: `True`...
def expand_modules(files_or_modules, black_list, black_list_re): """take a list of files/modules/packages and return the list of tuple (file, module name) which have to be actually checked """ result = [] errors = [] for something in files_or_modules: if basename(something) in black_list...
def register_plugins(linter, directory): """load all module and package in the given directory, looking for a 'register' function in each one, used to register pylint checkers """ imported = {} for filename in listdir(directory): base, extension = splitext(filename) if base in import...
def get_global_option(checker, option, default=None): """ 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. ...
def _splitstrip(string, sep=","): """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', ...
def _unquote(string): """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) """ if not string: return string ...
def _comment(string): """return string as a comment""" lines = [line.strip() for line in string.splitlines()] return "# " + ("%s# " % linesep).join(lines)
def _format_option_value(optdict, value): """return the user input's value from a 'compiled' value""" if isinstance(value, (list, tuple)): value = ",".join(_format_option_value(optdict, item) for item in value) elif isinstance(value, dict): value = ",".join("%s:%s" % (k, v) for k, v in value...
def format_section(stream, section, options, doc=None): """format an options section using the INI format""" if doc: print(_comment(doc), file=stream) print("[%s]" % section, file=stream) _ini_format(stream, options)
def _ini_format(stream, options): """format options using the INI format""" for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optdict.get("help") if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent="# ") ...
def insert(self, index, child): """insert a child node""" self.children.insert(index, child) child.parent = self
def _get_visit_name(self): """ return the visit name for the mixed class. When calling 'accept', the method <'visit_' + name returned by this method> will be called on the visitor """ try: # pylint: disable=no-member return self.TYPE.replace("-", "...
def append(self, child): """overridden to detect problems easily""" assert child not in self.parents() VNode.append(self, child)
def parents(self): """return the ancestor nodes""" assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
def format(self, layout, stream=None, encoding=None): """format and write the given layout into the stream object unicode policy: unicode strings may be found in the layout; try to call stream.write with it, but give it back encoded using the given encoding if it fails """ ...
def get_table_content(self, table): """trick to get table content without actually writing it return an aligned list of lists containing table cells values as string """ result = [[]] cols = table.cols for cell in self.compute_content(table): if cols == 0: ...
def compute_content(self, layout): """trick to compute the formatting of children layout before actually writing it return an iterator on strings (one for each child element) """ # Patch the underlying output stream with a fresh-generated stream, # which is used to store...
def collect_block_lines(self, msgs_store, module_node): """Walk the AST to collect block level options line numbers.""" for msg, lines in self._module_msgs_state.items(): self._raw_module_msgs_state[msg] = lines.copy() orig_state = self._module_msgs_state.copy() self._module_...