_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q269400
register
test
def register(linter): """Register the reporter classes with the linter.""" linter.register_reporter(TextReporter) linter.register_reporter(ParseableTextReporter)
python
{ "resource": "" }
q269401
TextReporter.handle_message
test
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)
python
{ "resource": "" }
q269402
TextReporter._display
test
def _display(self, layout): """launch layouts display""" print(file=self.out)
python
{ "resource": "" }
q269403
ColorizedTextReporter.handle_message
test
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( "************* Module %s" % msg.module, color, style ) else: modsep = colorize_ansi("************* %s" % msg.module, color, style) self.writeln(modsep)
python
{ "resource": "" }
q269404
VCGPrinter.open_graph
test
def open_graph(self, **args): """open a vcg graph """ self._stream.write("%sgraph:{\n" % self._indent)
python
{ "resource": "" }
q269405
VCGPrinter.node
test
def node(self, title, **args): """draw a node """ self._stream.write('%snode: {title:"%s"' % (self._indent, title))
python
{ "resource": "" }
q269406
VCGPrinter.edge
test
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"'
python
{ "resource": "" }
q269407
StringFormatChecker._check_new_format
test
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 # redefinitions of the original string. # For more details, see issue 287. # # Note that there may not be any left side at all, if the format method # has been assigned to another variable. See issue 351. For example: # # fmt = 'some string {}'.format # fmt('arg') if isinstance(node.func, astroid.Attribute) and not isinstance( node.func.expr, astroid.Const ): return if node.starargs or node.kwargs: return try: strnode = next(func.bound.infer()) except astroid.InferenceError: return if not (isinstance(strnode, astroid.Const) and isinstance(strnode.value, str)): return try: call_site = CallSite.from_call(node) except astroid.InferenceError: return try: fields, num_args, manual_pos = utils.parse_format_method_string( strnode.value ) except utils.IncompleteFormatString: self.add_message("bad-format-string", node=node) return positional_arguments = call_site.positional_arguments named_arguments = call_site.keyword_arguments named_fields = {field[0] for field in fields if isinstance(field[0], str)} if num_args and manual_pos: self.add_message("format-combined-specification", node=node) return check_args = False # Consider "{[0]} {[1]}" as num_args. num_args += sum(1 for field in named_fields if field == "") if named_fields: for field in named_fields: if field and field not in named_arguments: self.add_message( "missing-format-argument-key", node=node, args=(field,) ) for field in named_arguments: if field not in named_fields:
python
{ "resource": "" }
q269408
StringConstantChecker.process_non_raw_string_token
test
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 number in the source. """ # Walk through the string; if we see a backslash then escape the next # character, and skip over it. If we see a non-escaped character, # alert, and continue. # # Accept a backslash when it escapes a backslash, or a quote, or # end-of-line, or one of the letters that introduce a special escape # sequence <http://docs.python.org/reference/lexical_analysis.html> # # TODO(mbp): Maybe give a separate warning about the rarely-used # \a \b \v \f? # # TODO(mbp): We could give the column of the problem character, but
python
{ "resource": "" }
q269409
TextWriter.visit_section
test
def visit_section(self, layout): """display a section as text """ self.section += 1 self.writeln()
python
{ "resource": "" }
q269410
TextWriter.visit_evaluationsection
test
def visit_evaluationsection(self, layout): """Display an evaluation section as a text.""" self.section += 1
python
{ "resource": "" }
q269411
TextWriter.visit_table
test
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):
python
{ "resource": "" }
q269412
TextWriter.default_table
test
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(" ") table_linesep = "\n+" + "+".join(["-" * w for w in cols_width]) + "+\n" headsep = "\n+" + "+".join(["=" * w for w in cols_width]) + "+\n" # FIXME: layout.cheaders self.write(table_linesep) for index, line in enumerate(table_content): self.write("|")
python
{ "resource": "" }
q269413
MessagesStore.add_renamed_message
test
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
python
{ "resource": "" }
q269414
MessagesStore.register_messages_from_checker
test
def register_messages_from_checker(self, checker): """Register all messages from a checker. :param BaseChecker checker: """
python
{ "resource": "" }
q269415
MessagesStore.register_message
test
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.symbol) self._check_msgid(message.msgid, message.symbol) for old_name in message.old_names: self._check_symbol(message.msgid, old_name[1])
python
{ "resource": "" }
q269416
MessagesStore._check_symbol
test
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 alternative_message = self._alternative_names.get(symbol) if alternative_message: if alternative_message.symbol == symbol: alternative_msgid = alternative_message.msgid else:
python
{ "resource": "" }
q269417
MessagesStore._raise_duplicate_symbol
test
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 a symbol is duplicated. """ symbols = [symbol, other_symbol]
python
{ "resource": "" }
q269418
MessagesStore._raise_duplicate_msg_id
test
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 msgid
python
{ "resource": "" }
q269419
MessagesStore.get_message_definitions
test
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 MessageDefinition :return: A message definition corresponding to msgid_or_symbol """ if msgid_or_symbol[1:].isdigit(): msgid_or_symbol = msgid_or_symbol.upper() for source in (self._alternative_names, self._messages_definitions): try:
python
{ "resource": "" }
q269420
MessagesStore.get_msg_display_string
test
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
python
{ "resource": "" }
q269421
MessagesStore.help_message
test
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))
python
{ "resource": "" }
q269422
MessagesStore.list_messages
test
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:
python
{ "resource": "" }
q269423
builder_inited
test
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_path = os.path.join(base_path, "pylint", "extensions") modules = [] doc_files = {} for filename in os.listdir(ext_path): name, ext = os.path.splitext(filename) if name[0] == "_" or name in DEPRECATED_MODULES: continue if ext == ".py": modules.append("pylint.extensions.%s" % name) elif ext == ".rst": doc_files["pylint.extensions." + name] = os.path.join(ext_path, filename) modules.sort() if not modules:
python
{ "resource": "" }
q269424
_cpu_count
test
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:
python
{ "resource": "" }
q269425
report_messages_stats
test
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["by_msg"].items() if not msg_id.startswith("I") ] )
python
{ "resource": "" }
q269426
fix_import_path
test
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 value upon exiting this context. """ orig = list(sys.path) changes = []
python
{ "resource": "" }
q269427
PyLinter.load_plugin_modules
test
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
python
{ "resource": "" }
q269428
PyLinter.load_plugin_configuration
test
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
python
{ "resource": "" }
q269429
PyLinter.set_option
test
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: meth = self._options_methods[optname] except KeyError: meth = self._bw_options_methods[optname] warnings.warn( "%s is deprecated, replace it by %s" % (optname, optname.split("-")[0]), DeprecationWarning, ) value = utils._check_csv(value) if isinstance(value, (list, tuple)): for _id in value: meth(_id, ignore_unknown=True)
python
{ "resource": "" }
q269430
PyLinter.register_checker
test
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 in checker.reports: self.register_report(r_id, r_title, r_cb, checker) self.register_options_provider(checker) if hasattr(checker,
python
{ "resource": "" }
q269431
PyLinter.disable_reporters
test
def disable_reporters(self): """disable all reporters""" for _reporters in
python
{ "resource": "" }
q269432
PyLinter.python3_porting_mode
test
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 # Python 3 porting checker. for msg_id in self._checker_messages("python3"): if msg_id.startswith("E"): self.enable(msg_id)
python
{ "resource": "" }
q269433
PyLinter.get_checkers
test
def get_checkers(self): """return all available checkers as a list""" return [self] + [ c
python
{ "resource": "" }
q269434
PyLinter.get_checker_names
test
def get_checker_names(self): """Get all the checker names that this linter knows about.""" current_checkers = self.get_checkers() return sorted(
python
{ "resource": "" }
q269435
PyLinter.prepare_checkers
test
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 in checker.msgs if self.is_message_enabled(msg)} if messages or
python
{ "resource": "" }
q269436
PyLinter.expand_files
test
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
python
{ "resource": "" }
q269437
PyLinter.set_current_module
test
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)
python
{ "resource": "" }
q269438
PyLinter.check_astroid_module
test
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.args[0]) return None if not ast_node.pure_python: self.add_message("raw-checker-failed", args=ast_node.name) else:
python
{ "resource": "" }
q269439
PyLinter._report_evaluation
test
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["statement"] == 0: return # get a global note for the code evaluation = self.config.evaluation try: note = eval(evaluation, {}, self.stats) # pylint: disable=eval-used except Exception as ex: msg = "An exception occurred while rating: %s" % ex else:
python
{ "resource": "" }
q269440
Run.cb_help_message
test
def cb_help_message(self, option, optname, value, parser): """optik callback for printing some help about a particular message"""
python
{ "resource": "" }
q269441
Run.cb_full_documentation
test
def cb_full_documentation(self, option, optname, value, parser): """optik callback for printing full documentation"""
python
{ "resource": "" }
q269442
Run.cb_list_messages
test
def cb_list_messages(self, option, optname, value, parser): # FIXME """optik callback for printing available messages"""
python
{ "resource": "" }
q269443
Run.cb_list_groups
test
def cb_list_groups(self, *args, **kwargs): """List all the check groups that pylint knows about These should be useful
python
{ "resource": "" }
q269444
normalize_text
test
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap(
python
{ "resource": "" }
q269445
get_module_and_frameid
test
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:
python
{ "resource": "" }
q269446
safe_decode
test
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,
python
{ "resource": "" }
q269447
_basename_in_blacklist_re
test
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
python
{ "resource": "" }
q269448
register_plugins
test
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 imported or base == "__pycache__": continue if ( extension in PY_EXTS and base != "__init__" or (not extension and isdir(join(directory, base))) ): try: module = modutils.load_module_from_file(join(directory, filename))
python
{ "resource": "" }
q269449
_comment
test
def _comment(string): """return string as a comment""" lines = [line.strip() for line
python
{ "resource": "" }
q269450
_format_option_value
test
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.items()) elif hasattr(value, "match"): # optdict.get('type') == 'regexp'
python
{ "resource": "" }
q269451
format_section
test
def format_section(stream, section, options, doc=None): """format an options section using the INI format""" if doc: print(_comment(doc), file=stream)
python
{ "resource": "" }
q269452
_ini_format
test
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="# ") print(file=stream) print(help_opt, file=stream) else: print(file=stream) if value is None: print("#%s=" % optname, file=stream) else: value
python
{ "resource": "" }
q269453
VNode.insert
test
def insert(self, index, child): """insert a child node"""
python
{ "resource": "" }
q269454
BaseLayout.append
test
def append(self, child): """overridden to detect problems easily"""
python
{ "resource": "" }
q269455
BaseLayout.parents
test
def parents(self): """return the ancestor nodes""" assert self.parent is not self if self.parent is None:
python
{ "resource": "" }
q269456
BaseWriter.format
test
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 """ if stream is None: stream = sys.stdout if not encoding:
python
{ "resource": "" }
q269457
BaseWriter.get_table_content
test
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: result.append([]) cols = table.cols
python
{ "resource": "" }
q269458
BaseWriter.compute_content
test
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,
python
{ "resource": "" }
q269459
FileState.collect_block_lines
test
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()
python
{ "resource": "" }
q269460
FileState.handle_ignored_message
test
def handle_ignored_message( self, state_scope, msgid, line, node, args, confidence ): # pylint: disable=unused-argument """Report an ignored message. state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG, depending on whether the message was disabled locally in the module, or globally. The other arguments are the same as for add_message.
python
{ "resource": "" }
q269461
ReportsHandlerMixIn.register_report
test
def register_report(self, reportid, r_title, r_cb, checker): """register a report reportid is the unique identifier for the report r_title the report's
python
{ "resource": "" }
q269462
ReportsHandlerMixIn.make_reports
test
def make_reports(self, stats, old_stats): """render registered reports""" sect = Section("Report", "%s statements analysed." % (self.stats["statement"])) for checker in self.report_order(): for reportid, r_title, r_cb in self._reports[checker]: if not self.report_is_enabled(reportid): continue report_sect = Section(r_title)
python
{ "resource": "" }
q269463
ReportsHandlerMixIn.add_stats
test
def add_stats(self, **kwargs): """add some stats entries to the statistic dictionary raise an AssertionError if there is a key conflict """ for key, value in kwargs.items(): if key[-1]
python
{ "resource": "" }
q269464
get_setters_property_name
test
def get_setters_property_name(node): """Get the name of the property that the given node is a setter for. :param node: The node to get the property name for. :type node: str :rtype: str or None :returns: The name of the property that the node is a setter for,
python
{ "resource": "" }
q269465
get_setters_property
test
def get_setters_property(node): """Get the property node for the given setter node. :param node: The node to get the property for. :type node: astroid.FunctionDef :rtype: astroid.FunctionDef or None :returns: The node relating to the property of the given setter node, or None if one could not be found. """ property_ = None property_name =
python
{ "resource": "" }
q269466
returns_something
test
def returns_something(return_node): """Check if a return node returns a value other than None. :param return_node: The return node to check. :type return_node: astroid.Return :rtype: bool :return: True if the return node returns a value other than None, False otherwise.
python
{ "resource": "" }
q269467
possible_exc_types
test
def possible_exc_types(node): """ Gets all of the possible raised exception types for the given raise node. .. note:: Caught exception types are ignored. :param node: The raise node to find exception types for. :type node: astroid.node_classes.NodeNG :returns: A list of exception types possibly raised by :param:`node`. :rtype: set(str) """ excs = [] if isinstance(node.exc, astroid.Name): inferred = utils.safe_infer(node.exc) if inferred: excs = [inferred.name] elif node.exc is None: handler = node.parent while handler and not isinstance(handler, astroid.ExceptHandler): handler = handler.parent if handler and handler.type: inferred_excs = astroid.unpack_infer(handler.type) excs = (exc.name for exc in inferred_excs if exc is not astroid.Uninferable) else: target = _get_raise_target(node) if isinstance(target, astroid.ClassDef): excs = [target.name] elif isinstance(target, astroid.FunctionDef): for ret in target.nodes_of_class(astroid.Return): if ret.frame() != target:
python
{ "resource": "" }
q269468
ByIdManagedMessagesChecker.process_module
test
def process_module(self, module): """inspect the source file to find messages activated or deactivated by id.""" managed_msgs = MessagesHandlerMixIn.get_by_id_managed_msgs() for (mod_name, msg_id, msg_symbol, lineno, is_disabled) in managed_msgs: if mod_name == module.name: if is_disabled: txt = "Id '{ident}' is used to disable '{symbol}' message emission".format( ident=msg_id, symbol=msg_symbol
python
{ "resource": "" }
q269469
EncodingChecker.process_module
test
def process_module(self, module): """inspect the source file to find encoding problem""" if module.file_encoding: encoding = module.file_encoding else: encoding = "ascii" with
python
{ "resource": "" }
q269470
EncodingChecker.process_tokens
test
def process_tokens(self, tokens): """inspect the source to find fixme problems""" if not self.config.notes: return comments = ( token_info for token_info in tokens if token_info.type == tokenize.COMMENT ) for comment in comments: comment_text = comment.string[1:].lstrip() # trim '#' and whitespaces # handle pylint disable clauses disable_option_match = OPTION_RGX.search(comment_text) if disable_option_match: try: _, value = disable_option_match.group(1).split("=", 1) values = [_val.strip().upper() for _val in value.split(",")] if set(values) & set(self.config.notes): continue except ValueError: self.add_message( "bad-inline-option",
python
{ "resource": "" }
q269471
_is_from_future_import
test
def _is_from_future_import(stmt, name): """Check if the name is a future import from another module.""" try: module = stmt.do_import_module(stmt.modname) except astroid.AstroidBuildingException: return None
python
{ "resource": "" }
q269472
in_for_else_branch
test
def in_for_else_branch(parent, stmt): """Returns True if stmt in inside the else branch for a parent For stmt.""" return isinstance(parent, astroid.For) and any(
python
{ "resource": "" }
q269473
overridden_method
test
def overridden_method(klass, name): """get overridden method if any""" try: parent = next(klass.local_attr_ancestors(name)) except (StopIteration, KeyError): return None try: meth_node = parent[name] except KeyError: # We have found an ancestor defining <name> but it's not in the local
python
{ "resource": "" }
q269474
_get_unpacking_extra_info
test
def _get_unpacking_extra_info(node, infered): """return extra information to add to the message for unpacking-non-sequence and unbalanced-tuple-unpacking errors """ more = "" infered_module = infered.root().name if node.root().name == infered_module: if node.lineno == infered.lineno: more = " %s"
python
{ "resource": "" }
q269475
_detect_global_scope
test
def _detect_global_scope(node, frame, defframe): """ 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: ... """ def_scope = scope = None if frame and frame.parent: scope = frame.parent.scope() if defframe and defframe.parent: def_scope = defframe.parent.scope() if isinstance(frame, astroid.FunctionDef): # If the parent of the current node is a # function, then it can be under its scope # (defined in, which doesn't concern us) or # the `->` part of annotations. The same goes # for annotations of function arguments, they'll have # their parent the Arguments node. if not isinstance(node.parent, (astroid.FunctionDef, astroid.Arguments)): return False elif any( not isinstance(f, (astroid.ClassDef, astroid.Module)) for f in (frame, defframe) ): # Not interested in other frames, since they are already # not in a global scope. return False break_scopes = [] for s in (scope, def_scope): # Look for parent scopes. If there is anything different
python
{ "resource": "" }
q269476
_assigned_locally
test
def _assigned_locally(name_node): """ Checks if name_node has corresponding assign statement in same scope """
python
{ "resource": "" }
q269477
NamesConsumer.mark_as_consumed
test
def mark_as_consumed(self, name, new_node): """ Mark the name as consumed and delete it from the to_consume dictionary
python
{ "resource": "" }
q269478
VariablesChecker.visit_global
test
def visit_global(self, node): """check names imported exists in the global scope""" frame = node.frame() if isinstance(frame, astroid.Module): self.add_message("global-at-module-level", node=node) return module = frame.root() default_message = True locals_ = node.scope().locals for name in node.names: try: assign_nodes = module.getattr(name) except astroid.NotFoundError: # unassigned global, skip assign_nodes = [] not_defined_locally_by_import = not any( isinstance(local, astroid.node_classes.Import) for local in locals_.get(name, ()) ) if not assign_nodes and not_defined_locally_by_import: self.add_message("global-variable-not-assigned", args=name, node=node) default_message = False continue for anode in assign_nodes: if (
python
{ "resource": "" }
q269479
VariablesChecker._ignore_class_scope
test
def _ignore_class_scope(self, node): """ 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 """ # Detect if we are in a local class scope, as an assignment. # For example, the following is fair game. # # class A: # b = 1 # c = lambda b=b: b * b # # class B: # tp = 1 # def func(self, arg: tp): # ... # class C: # tp = 2 # def func(self, arg=tp):
python
{ "resource": "" }
q269480
VariablesChecker._has_homonym_in_upper_function_scope
test
def _has_homonym_in_upper_function_scope(self, node, index): """ 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
python
{ "resource": "" }
q269481
VariablesChecker._check_unpacking
test
def _check_unpacking(self, infered, node, targets): """ Check for unbalanced tuple unpacking and unpacking non sequences. """ if utils.is_inside_abstract_class(node): return if utils.is_comprehension(node): return if infered is astroid.Uninferable: return if ( isinstance(infered.parent, astroid.Arguments) and isinstance(node.value, astroid.Name) and node.value.name == infered.parent.vararg ): # Variable-length argument, we can't determine the length. return if isinstance(infered, (astroid.Tuple, astroid.List)): # attempt to check unpacking is properly balanced values = infered.itered() if len(targets) != len(values): # Check if we have starred nodes. if any(isinstance(target, astroid.Starred) for target in targets): return self.add_message(
python
{ "resource": "" }
q269482
VariablesChecker3k._check_metaclasses
test
def _check_metaclasses(self, node): """ Update consumption analysis for metaclasses. """ consumed = [] # [(scope_locals, consumed_key)] for child_node in node.get_children(): if isinstance(child_node, astroid.ClassDef):
python
{ "resource": "" }
q269483
get_packages
test
def get_packages(directory, prefix): """return a list of subpackages for the given directory""" result = [] for package in os.listdir(directory): absfile = join(directory, package) if isdir(absfile): if exists(join(absfile, "__init__.py")):
python
{ "resource": "" }
q269484
install
test
def install(**kwargs): """setup entry point""" if USE_SETUPTOOLS: if "--force-manifest" in sys.argv: sys.argv.remove("--force-manifest") packages = [modname] + get_packages(join(base_dir, "pylint"), modname) if USE_SETUPTOOLS: if install_requires: kwargs["install_requires"] = install_requires kwargs["dependency_links"] = dependency_links kwargs["entry_points"] = { "console_scripts": [ "pylint = pylint:run_pylint", "epylint = pylint:run_epylint", "pyreverse = pylint:run_pyreverse", "symilar = pylint:run_symilar", ] } kwargs["packages"] = packages cmdclass = {"install_lib": MyInstallLib, "build_py": build_py} if easy_install_lib: cmdclass["easy_install"] = easy_install return setup(
python
{ "resource": "" }
q269485
MyInstallLib.run
test
def run(self): """overridden from install_lib class""" install_lib.install_lib.run(self) # manually install included directories if any if include_dirs: for directory in include_dirs: dest = join(self.install_dir, directory) if sys.version_info >= (3, 0): exclude = {"invalid_encoded_data*", "unknown_encoding*"} else:
python
{ "resource": "" }
q269486
report_similarities
test
def report_similarities(sect, stats, old_stats): """make a layout with some stats about duplication""" lines = ["", "now", "previous", "difference"] lines += table_lines_from_stats( stats, old_stats,
python
{ "resource": "" }
q269487
Run
test
def Run(argv=None): """standalone command line access point""" if argv is None: argv = sys.argv[1:] from getopt import getopt s_opts = "hdi" l_opts = ( "help", "duplicates=", "ignore-comments", "ignore-imports", "ignore-docstrings", ) min_lines = 4 ignore_comments = False ignore_docstrings = False ignore_imports = False opts, args = getopt(argv, s_opts, l_opts) for opt, val in opts: if opt in ("-d", "--duplicates"): min_lines = int(val) elif opt in ("-h", "--help"): usage() elif
python
{ "resource": "" }
q269488
Similar.append_stream
test
def append_stream(self, streamid, stream, encoding=None): """append a file to search for similarities""" if encoding is None: readlines = stream.readlines else: readlines = decoding_stream(stream, encoding).readlines try: self.linesets.append( LineSet( streamid,
python
{ "resource": "" }
q269489
Similar._compute_sims
test
def _compute_sims(self): """compute similarities in appended files""" no_duplicates = defaultdict(list) for num, lineset1, idx1, lineset2, idx2 in self._iter_sims(): duplicate = no_duplicates[num] for couples in duplicate: if (lineset1, idx1) in couples or (lineset2, idx2) in couples: couples.add((lineset1, idx1)) couples.add((lineset2, idx2)) break
python
{ "resource": "" }
q269490
Similar._display_sims
test
def _display_sims(self, sims): """display computed similarities on stdout""" nb_lignes_dupliquees = 0 for num, couples in sims: print() print(num, "similar lines in", len(couples), "files") couples = sorted(couples) for lineset, idx in couples: print("==%s:%s" % (lineset.name, idx)) # pylint: disable=W0631 for line in lineset._real_lines[idx : idx + num]: print(" ", line.rstrip()) nb_lignes_dupliquees += num * (len(couples)
python
{ "resource": "" }
q269491
Similar._find_common
test
def _find_common(self, lineset1, lineset2): """find similarities in the two given linesets""" lines1 = lineset1.enumerate_stripped lines2 = lineset2.enumerate_stripped find = lineset2.find index1 = 0 min_lines = self.min_lines while index1 < len(lineset1): skip = 1 num = 0 for index2 in find(lineset1[index1]): non_blank = 0 for num, ((_, line1), (_, line2)) in enumerate( zip(lines1(index1), lines2(index2)) ): if line1 != line2: if non_blank > min_lines: yield num, lineset1, index1, lineset2, index2
python
{ "resource": "" }
q269492
Similar._iter_sims
test
def _iter_sims(self): """iterate on similarities among all files, by making a cartesian product """ for idx, lineset in enumerate(self.linesets[:-1]): for lineset2
python
{ "resource": "" }
q269493
LineSet.enumerate_stripped
test
def enumerate_stripped(self, start_at=0): """return an iterator on stripped lines, starting from a given index if specified, else 0 """ idx = start_at if start_at: lines = self._stripped_lines[start_at:]
python
{ "resource": "" }
q269494
LineSet._mk_index
test
def _mk_index(self): """create the index for this set""" index = defaultdict(list) for line_no, line in enumerate(self._stripped_lines):
python
{ "resource": "" }
q269495
_definition_equivalent_to_call
test
def _definition_equivalent_to_call(definition, call): """Check if a definition signature is equivalent to a call.""" if definition.kwargs: same_kw_variadics = definition.kwargs in call.starred_kws else: same_kw_variadics = not call.starred_kws if definition.varargs: same_args_variadics = definition.varargs in call.starred_args else: same_args_variadics = not call.starred_args same_kwonlyargs = all(kw in call.kws for kw in definition.kwonlyargs) same_args = definition.args == call.args
python
{ "resource": "" }
q269496
_check_arg_equality
test
def _check_arg_equality(node_a, node_b, attr_name): """ Check equality of nodes based on the comparison of their attributes named attr_name. Args: node_a (astroid.node): first node to compare. node_b (astroid.node): second node to compare. attr_name (str): name of the nodes attribute to use for comparison.
python
{ "resource": "" }
q269497
_has_different_parameters_default_value
test
def _has_different_parameters_default_value(original, overridden): """ Check if original and overridden methods arguments have different default values Return True if one of the overridden arguments has a default value different from the default value of the original argument If one of the method doesn't have argument (.args is None) return False """ if original.args is None or overridden.args is None: return False all_args = chain(original.args, original.kwonlyargs) original_param_names = [param.name for param in all_args] default_missing = object() for param_name in original_param_names: try: original_default = original.default_value(param_name) except astroid.exceptions.NoDefault: original_default = default_missing try: overridden_default = overridden.default_value(param_name) except astroid.exceptions.NoDefault: overridden_default = default_missing default_list = [ arg == default_missing for arg in (original_default, overridden_default) ] if any(default_list) and not all(default_list): # Only one arg has no default value return True astroid_type_compared_attr = { astroid.Const: "value",
python
{ "resource": "" }
q269498
_different_parameters
test
def _different_parameters(original, overridden, dummy_parameter_regex): """Determine if the two methods have different parameters They are considered to have different parameters if: * they have different positional parameters, including different names * one of the methods is having variadics, while the other is not * they have different keyword only parameters. """ original_parameters = _positional_parameters(original) overridden_parameters = _positional_parameters(overridden) different_positional = _has_different_parameters( original_parameters, overridden_parameters, dummy_parameter_regex ) different_kwonly = _has_different_parameters(
python
{ "resource": "" }
q269499
_safe_infer_call_result
test
def _safe_infer_call_result(node, caller, context=None): """ Safely infer the return value of a function. Returns None if inference failed or if there is some ambiguity (more than one node has been inferred). Otherwise returns infered value. """ try: inferit = node.infer_call_result(caller, context=context) value = next(inferit) except astroid.InferenceError: return None # inference failed
python
{ "resource": "" }