_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q269500
ScopeAccessMap.set_accessed
test
def set_accessed(self, node): """Set the given node as accessed.""" frame = node_frame_class(node)
python
{ "resource": "" }
q269501
ClassChecker.visit_classdef
test
def visit_classdef(self, node): """init visit variable _accessed """ self._check_bases_classes(node) # if not an exception or a metaclass if node.type == "class" and has_known_bases(node): try: node.local_attr("__init__")
python
{ "resource": "" }
q269502
ClassChecker._check_consistent_mro
test
def _check_consistent_mro(self, node): """Detect that a class has a consistent mro or duplicate bases.""" try: node.mro() except InconsistentMroError: self.add_message("inconsistent-mro", args=node.name, node=node) except DuplicateBasesError:
python
{ "resource": "" }
q269503
ClassChecker._check_proper_bases
test
def _check_proper_bases(self, node): """ Detect that a class inherits something which is not a class or a type. """ for base in node.bases: ancestor = safe_infer(base) if ancestor in (astroid.Uninferable, None): continue if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of( "%s.type" % (BUILTINS,) ): continue if not isinstance(ancestor, astroid.ClassDef) or _is_invalid_base_class(
python
{ "resource": "" }
q269504
ClassChecker.visit_functiondef
test
def visit_functiondef(self, node): """check method arguments, overriding""" # ignore actual functions if not node.is_method(): return self._check_useless_super_delegation(node) klass = node.parent.frame() self._meth_could_be_func = True # check first argument is self if this is actually a method self._check_first_arg_for_type(node, klass.type == "metaclass") if node.name == "__init__": self._check_init(node) return # check signature if the method overloads inherited method for overridden in klass.local_attr_ancestors(node.name): # get astroid for the searched method try: meth_node = overridden[node.name] except KeyError: # we have found the method but it's not in the local # dictionary. # This may happen with astroid build from living objects continue if not isinstance(meth_node, astroid.FunctionDef): continue self._check_signature(node, meth_node, "overridden", klass) break if node.decorators: for decorator in node.decorators.nodes: if isinstance(decorator, astroid.Attribute) and decorator.attrname in ( "getter", "setter", "deleter",
python
{ "resource": "" }
q269505
ClassChecker._check_useless_super_delegation
test
def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to delegate an operation to the rest of the MRO, and if the method called is the same as the current one, the arguments passed to super() are the same as the parameters that were passed to this method, then the method could be removed altogether, by letting other implementation to take precedence. """ if ( not function.is_method() # With decorators is a change of use or function.decorators ): return body = function.body if len(body) != 1: # Multiple statements, which means this overridden method # could do multiple things we are not aware of. return statement = body[0] if not isinstance(statement, (astroid.Expr, astroid.Return)): # Doing something else than what we are interested into. return call = statement.value if ( not isinstance(call, astroid.Call) # Not a super() attribute access. or not isinstance(call.func, astroid.Attribute) ): return # Should be a super call. try: super_call = next(call.func.expr.infer()) except astroid.InferenceError: return else: if not isinstance(super_call, objects.Super): return # The name should be the same. if call.func.attrname != function.name: return # Should be a super call with the MRO pointer being the # current class and the type being the current instance. current_scope = function.parent.scope() if ( super_call.mro_pointer != current_scope or not isinstance(super_call.type, astroid.Instance) or super_call.type.name != current_scope.name ): return #  Check values of default args klass = function.parent.frame() meth_node = None for overridden in klass.local_attr_ancestors(function.name): # get astroid for the searched method
python
{ "resource": "" }
q269506
ClassChecker.leave_functiondef
test
def leave_functiondef(self, node): """on method node, check if this method couldn't be a function ignore class, static and abstract methods, initializer, methods overridden from a parent class. """ if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled("no-self-use"):
python
{ "resource": "" }
q269507
ClassChecker._check_in_slots
test
def _check_in_slots(self, node): """ Check that the given AssignAttr node is defined in the class slots. """ inferred = safe_infer(node.expr) if not isinstance(inferred, astroid.Instance): return klass = inferred._proxied if not has_known_bases(klass): return if "__slots__" not in klass.locals or not klass.newstyle: return slots = klass.slots() if slots is None: return # If any ancestor doesn't use slots, the slots # defined for this class are superfluous. if any( "__slots__" not in ancestor.locals and ancestor.name != "object" for ancestor in klass.ancestors() ): return if not any(slot.value == node.attrname for slot in slots): # If we have a '__dict__' in slots, then # assigning any name is valid. if not any(slot.value == "__dict__" for slot in slots): if _is_attribute_property(node.attrname, klass):
python
{ "resource": "" }
q269508
ClassChecker.visit_name
test
def visit_name(self, node): """check if the name handle an access to a class member if so, register it
python
{ "resource": "" }
q269509
ClassChecker._check_accessed_members
test
def _check_accessed_members(self, node, accessed): """check that accessed members are defined""" # XXX refactor, probably much simpler now that E0201 is in type checker excs = ("AttributeError", "Exception", "BaseException") for attr, nodes in accessed.items(): try: # is it a class attribute ? node.local_attr(attr) # yes, stop here continue except astroid.NotFoundError: pass # is it an instance attribute of a parent class ? try: next(node.instance_attr_ancestors(attr)) # yes, stop here continue except StopIteration: pass # is it an instance attribute ? try: defstmts = node.instance_attr(attr) except astroid.NotFoundError: pass else: # filter out augment assignment nodes defstmts = [stmt for stmt in defstmts if stmt not in nodes] if not defstmts: # only augment assignment for this node, no-member should be # triggered by the typecheck checker continue # filter defstmts to only pick the first one when there are # several assignments in the same scope scope = defstmts[0].scope() defstmts = [ stmt for i, stmt in enumerate(defstmts) if i == 0 or stmt.scope() is not scope ]
python
{ "resource": "" }
q269510
ClassChecker._check_bases_classes
test
def _check_bases_classes(self, node): """check that the given class node implements abstract methods from base classes """ def is_abstract(method): return method.is_abstract(pass_is_abstract=False) # check if this class abstract if class_is_abstract(node): return methods = sorted( unimplemented_abstract_methods(node, is_abstract).items(), key=lambda item: item[0], ) for name, method in methods: owner = method.parent.frame() if owner is node:
python
{ "resource": "" }
q269511
ClassChecker._check_signature
test
def _check_signature(self, method1, refmethod, class_type, cls): """check that the signature of the two given methods match """ if not ( isinstance(method1, astroid.FunctionDef) and isinstance(refmethod, astroid.FunctionDef) ): self.add_message( "method-check-failed", args=(method1, refmethod), node=method1 ) return instance = cls.instantiate_class() method1 = function_to_method(method1, instance) refmethod = function_to_method(refmethod, instance) # Don't care about functions with unknown argument (builtins). if method1.args.args is None or refmethod.args.args is None: return # Ignore private to class methods. if is_attr_private(method1.name): return # Ignore setters, they have an implicit extra argument, # which shouldn't be taken in consideration. if method1.decorators: for decorator in method1.decorators.nodes: if (
python
{ "resource": "" }
q269512
ClassChecker._is_mandatory_method_param
test
def _is_mandatory_method_param(self, node): """Check if astroid.Name corresponds to first attribute variable name Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return (
python
{ "resource": "" }
q269513
_is_raising
test
def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body:
python
{ "resource": "" }
q269514
ExceptionsChecker._check_bad_exception_context
test
def _check_bad_exception_context(self, node): """Verify that the exception context is properly set. An exception context can be only `None` or an exception. """ cause = utils.safe_infer(node.cause) if cause in (astroid.Uninferable, None): return if isinstance(cause, astroid.Const):
python
{ "resource": "" }
q269515
NewStyleConflictChecker.visit_functiondef
test
def visit_functiondef(self, node): """check use of super""" # ignore actual functions or method within a new style class if not node.is_method(): return klass = node.parent.frame() for stmt in node.nodes_of_class(astroid.Call): if node_frame_class(stmt) != node_frame_class(node): # Don't look down in other scopes. continue expr = stmt.func if not isinstance(expr, astroid.Attribute): continue call = expr.expr # skip the test if using super if not ( isinstance(call, astroid.Call) and isinstance(call.func, astroid.Name) and call.func.name == "super" ): continue if not klass.newstyle and has_known_bases(klass): # super should not be used on an old style class continue else: # super first arg should be the class if not call.args: if sys.version_info[0] == 3: # unless Python 3 continue else: self.add_message("missing-super-argument", node=call) continue # calling super(type(self), self) can lead to recursion loop # in derived classes arg0 = call.args[0] if ( isinstance(arg0, astroid.Call) and isinstance(arg0.func, astroid.Name) and arg0.func.name == "type" ): self.add_message("bad-super-call", node=call, args=("type",)) continue # calling super(self.__class__, self) can lead to recursion loop # in derived classes
python
{ "resource": "" }
q269516
BaseReporter.display_reports
test
def display_reports(self, layout): """display results encapsulated in the layout tree""" self.section = 0 if hasattr(layout, "report_id"):
python
{ "resource": "" }
q269517
_is_typing_namedtuple
test
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool: """Check if a class node is a typing.NamedTuple class""" for base in node.ancestors(): if
python
{ "resource": "" }
q269518
_is_enum_class
test
def _is_enum_class(node: astroid.ClassDef) -> bool: """Check if a class definition defines an Enum class. :param node: The class node to check. :type node: astroid.ClassDef :returns: True if the given node represents an Enum class. False otherwise. :rtype: bool """ for base in node.bases: try: inferred_bases = base.inferred() except astroid.InferenceError: continue for ancestor in
python
{ "resource": "" }
q269519
_is_dataclass
test
def _is_dataclass(node: astroid.ClassDef) -> bool: """Check if a class definition defines a Python 3.7+ dataclass :param node: The class node to check. :type node: astroid.ClassDef :returns: True if the given node represents a dataclass class. False otherwise. :rtype: bool """ if not node.decorators: return False
python
{ "resource": "" }
q269520
MisdesignChecker.open
test
def open(self): """initialize visit variables""" self.stats = self.linter.add_stats() self._returns = []
python
{ "resource": "" }
q269521
MisdesignChecker.visit_classdef
test
def visit_classdef(self, node): """check size of inheritance hierarchy and number of instance attributes """ nb_parents = len(list(node.ancestors())) if nb_parents > self.config.max_parents: self.add_message(
python
{ "resource": "" }
q269522
MisdesignChecker.leave_classdef
test
def leave_classdef(self, node): """check number of public methods""" my_methods = sum( 1 for method in node.mymethods() if not method.name.startswith("_") ) # Does the class contain less than n public methods ? # This checks only the methods defined in the current class, # since the user might not have control over the classes # from the ancestors. It avoids some false positives # for classes such as unittest.TestCase, which provides # a lot of assert methods. It doesn't make sense to warn # when the user subclasses TestCase to add his own tests. if my_methods > self.config.max_public_methods: self.add_message( "too-many-public-methods", node=node, args=(my_methods, self.config.max_public_methods), ) # Stop here for exception, metaclass, interface classes and other # classes for which we don't need to count the methods. if ( node.type != "class"
python
{ "resource": "" }
q269523
MisdesignChecker.visit_if
test
def visit_if(self, node): """increments the branches counter and checks boolean expressions""" self._check_boolean_expressions(node) branches = 1
python
{ "resource": "" }
q269524
MisdesignChecker._check_boolean_expressions
test
def _check_boolean_expressions(self, node): """Go through "if" node `node` and counts its boolean expressions if the "if" node test is a BoolOp node """ condition = node.test if not isinstance(condition, BoolOp): return nb_bool_expr = _count_boolean_expressions(condition) if nb_bool_expr >
python
{ "resource": "" }
q269525
SpellingChecker._check_docstring
test
def _check_docstring(self, node): """check the node has any spelling errors""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring
python
{ "resource": "" }
q269526
Message.format
test
def format(self, template): """Format the message according to the given template. The template format is the one of the format method : cf. http://docs.python.org/2/library/string.html#formatstrings """ #
python
{ "resource": "" }
q269527
_is_trailing_comma
test
def _is_trailing_comma(tokens, index): """Check if the given token is a trailing comma :param tokens: Sequence of modules tokens :type tokens: list[tokenize.TokenInfo] :param int index: Index of token under check in tokens :returns: True if the token is a comma which trails an expression :rtype: bool """ token = tokens[index] if token.exact_type != tokenize.COMMA: return False # Must have remaining tokens on the same line such as NEWLINE left_tokens = itertools.islice(tokens, index + 1, None) same_line_remaining_tokens = list( itertools.takewhile( lambda other_token, _token=token: other_token.start[0] == _token.start[0],
python
{ "resource": "" }
q269528
RefactoringChecker._is_actual_elif
test
def _is_actual_elif(self, node): """Check if the given node is an actual elif This is a problem we're having with the builtin ast module, which splits `elif` branches into a separate if statement. Unfortunately we need to know the exact
python
{ "resource": "" }
q269529
RefactoringChecker._check_simplifiable_if
test
def _check_simplifiable_if(self, node): """Check if the given if node can be simplified. The if statement can be reduced to a boolean expression in some cases. For instance, if there are two branches and both of them return a boolean value that depends on the result of the statement's test, then this can be reduced to `bool(test)` without losing any functionality. """ if self._is_actual_elif(node): # Not interested in if statements with multiple branches. return if len(node.orelse) != 1 or len(node.body) != 1: return # Check if both branches can be reduced. first_branch = node.body[0] else_branch = node.orelse[0] if isinstance(first_branch, astroid.Return): if not isinstance(else_branch, astroid.Return): return first_branch_is_bool = self._is_bool_const(first_branch) else_branch_is_bool = self._is_bool_const(else_branch) reduced_to = "'return bool(test)'" elif isinstance(first_branch, astroid.Assign): if not isinstance(else_branch, astroid.Assign): return # Check if we assign to the same value first_branch_targets = [ target.name for target in first_branch.targets if isinstance(target, astroid.AssignName) ] else_branch_targets = [ target.name for target in else_branch.targets if isinstance(target, astroid.AssignName) ] if not first_branch_targets or not else_branch_targets: return if sorted(first_branch_targets) != sorted(else_branch_targets): return first_branch_is_bool = self._is_bool_const(first_branch) else_branch_is_bool = self._is_bool_const(else_branch) reduced_to = "'var = bool(test)'" else:
python
{ "resource": "" }
q269530
RefactoringChecker._check_stop_iteration_inside_generator
test
def _check_stop_iteration_inside_generator(self, node): """Check if an exception of type StopIteration is raised inside a generator""" frame = node.frame() if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator(): return if utils.node_ignores_exception(node, StopIteration): return if not node.exc: return exc = utils.safe_infer(node.exc)
python
{ "resource": "" }
q269531
RefactoringChecker._check_exception_inherit_from_stopiteration
test
def _check_exception_inherit_from_stopiteration(exc): """Return True if the exception node in argument inherit from StopIteration"""
python
{ "resource": "" }
q269532
RefactoringChecker._check_raising_stopiteration_in_generator_next_call
test
def _check_raising_stopiteration_in_generator_next_call(self, node): """Check if a StopIteration exception is raised by the call to next function If the next value has a default value, then do not add message. :param node: Check to see if this Call node is a next function :type node: :class:`astroid.node_classes.Call` """ def _looks_like_infinite_iterator(param): inferred = utils.safe_infer(param) if inferred: return inferred.qname() in KNOWN_INFINITE_ITERATORS return False if isinstance(node.func, astroid.Attribute): # A next() method, which is now what we want. return inferred = utils.safe_infer(node.func) if getattr(inferred, "name", "") == "next": frame = node.frame() # The next builtin can only have up to two # positional arguments and no keyword arguments
python
{ "resource": "" }
q269533
RefactoringChecker._check_nested_blocks
test
def _check_nested_blocks(self, node): """Update and check the number of nested blocks """ # only check block levels inside functions or methods if not isinstance(node.scope(), astroid.FunctionDef): return # messages are triggered on leaving the nested block. Here we save the # stack in case the current node isn't nested in the previous one nested_blocks = self._nested_blocks[:] if node.parent == node.scope(): self._nested_blocks = [node] else: # go through ancestors from the most nested to the less for ancestor_node in reversed(self._nested_blocks): if ancestor_node == node.parent: break self._nested_blocks.pop() # if the node is an elif, this should not be another nesting level
python
{ "resource": "" }
q269534
RefactoringChecker._duplicated_isinstance_types
test
def _duplicated_isinstance_types(node): """Get the duplicated types from the underlying isinstance calls. :param astroid.BoolOp node: Node which should contain a bunch of isinstance calls. :returns: Dictionary of the comparison objects from the isinstance calls, to duplicate values from consecutive calls. :rtype: dict """ duplicated_objects = set() all_types = collections.defaultdict(set) for call in node.values: if not isinstance(call, astroid.Call) or len(call.args) != 2: continue inferred = utils.safe_infer(call.func) if not inferred or not utils.is_builtin_object(inferred): continue if inferred.name != "isinstance": continue isinstance_object = call.args[0].as_string() isinstance_types = call.args[1] if isinstance_object in all_types: duplicated_objects.add(isinstance_object)
python
{ "resource": "" }
q269535
RefactoringChecker._check_consider_merging_isinstance
test
def _check_consider_merging_isinstance(self, node): """Check isinstance calls which can be merged together.""" if node.op != "or": return first_args = self._duplicated_isinstance_types(node) for duplicated_name, class_names in first_args.items(): names = sorted(name for name in class_names)
python
{ "resource": "" }
q269536
RefactoringChecker._check_chained_comparison
test
def _check_chained_comparison(self, node): """Check if there is any chained comparison in the expression. Add a refactoring message if a boolOp contains comparison like a < b and b < c, which can be chained as a < b < c. Care is taken to avoid simplifying a < b < c and b < d. """ if node.op != "and" or len(node.values) < 2: return def _find_lower_upper_bounds(comparison_node, uses): left_operand = comparison_node.left for operator, right_operand in comparison_node.ops: for operand in (left_operand, right_operand): value = None if isinstance(operand, astroid.Name): value = operand.name elif isinstance(operand, astroid.Const): value = operand.value if value is None: continue if operator in ("<", "<="): if operand is left_operand: uses[value]["lower_bound"].add(comparison_node) elif operand is right_operand: uses[value]["upper_bound"].add(comparison_node) elif operator in (">", ">="): if operand is left_operand: uses[value]["upper_bound"].add(comparison_node) elif operand is right_operand:
python
{ "resource": "" }
q269537
RefactoringChecker._is_and_or_ternary
test
def _is_and_or_ternary(node): """ Returns true if node is 'condition and true_value or false_value' form. All of: condition, true_value and false_value should not be a complex boolean expression """ return ( isinstance(node, astroid.BoolOp) and node.op == "or" and len(node.values) == 2
python
{ "resource": "" }
q269538
RefactoringChecker._check_consistent_returns
test
def _check_consistent_returns(self, node): """Check that all return statements inside a function are consistent. Return statements are consistent if: - all returns are explicit and if there is no implicit return; - all returns are empty and if there is, possibly, an implicit return. Args: node (astroid.FunctionDef): the function holding the return statements. """ # explicit return statements are those with a not None value explicit_returns = [ _node for _node in self._return_nodes[node.name] if _node.value is not None
python
{ "resource": "" }
q269539
RefactoringChecker._is_node_return_ended
test
def _is_node_return_ended(self, node): """Check if the node ends with an explicit return statement. Args: node (astroid.NodeNG): node to be checked. Returns: bool: True if the node ends with an explicit statement, False otherwise. """ #  Recursion base case if isinstance(node, astroid.Return): return True if isinstance(node, astroid.Call): try: funcdef_node = node.func.inferred()[0] if self._is_function_def_never_returning(funcdef_node): return True except astroid.InferenceError: pass # Avoid the check inside while loop as we don't know #  if they will be completed if isinstance(node, astroid.While): return True if isinstance(node, astroid.Raise): # a Raise statement doesn't need to end with a return statement # but if the exception raised is handled, then the handler has to # ends with a return statement if not node.exc: # Ignore bare raises return True if not utils.is_node_inside_try_except(node): # If the raise statement is not inside a try/except statement #  then the exception is raised and cannot be caught. No need #  to infer it. return True exc = utils.safe_infer(node.exc) if exc is None or exc is astroid.Uninferable: return False exc_name = exc.pytype().split(".")[-1] handlers = utils.get_exception_handlers(node, exc_name) handlers = list(handlers) if handlers is not None else [] if handlers: # among all the handlers handling the exception at least one # must end with a return statement return any( self._is_node_return_ended(_handler) for _handler in handlers
python
{ "resource": "" }
q269540
RecommandationChecker.visit_for
test
def visit_for(self, node): """Emit a convention whenever range and len are used for indexing.""" # Verify that we have a `range([start], len(...), [stop])` call and # that the object which is iterated is used as a subscript in the # body of the for. # Is it a proper range call? if not isinstance(node.iter, astroid.Call): return if not self._is_builtin(node.iter.func, "range"): return if len(node.iter.args) == 2 and not _is_constant_zero(node.iter.args[0]): return if len(node.iter.args) > 2: return # Is it a proper len call? if not isinstance(node.iter.args[-1], astroid.Call): return second_func = node.iter.args[-1].func if not self._is_builtin(second_func, "len"): return len_args = node.iter.args[-1].args if not len_args or len(len_args) != 1: return iterating_object = len_args[0] if not isinstance(iterating_object, astroid.Name): return # If we're defining __iter__ on self, enumerate won't work scope = node.scope() if iterating_object.name == "self" and scope.name == "__iter__": return # Verify that the body of the for loop uses a subscript # with the object that was iterated. This uses some heuristics # in order to make sure that the same object is used in the
python
{ "resource": "" }
q269541
_check_graphviz_available
test
def _check_graphviz_available(output_format): """check if we need graphviz for different output format""" try: subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: print( "The output format '%s' is currently not available.\n"
python
{ "resource": "" }
q269542
Run.run
test
def run(self, args): """checking arguments and run project""" if not args: print(self.help()) return 1 # insert current working directory to the python path to recognize # dependencies to local modules even if cwd is not in the PYTHONPATH sys.path.insert(0, os.getcwd()) try: project = project_from_files( args, project_name=self.config.project, black_list=self.config.black_list, )
python
{ "resource": "" }
q269543
DiagramWriter.write_packages
test
def write_packages(self, diagram): """write a package diagram""" # sorted to get predictable (hence testable) results for i, obj in enumerate(sorted(diagram.modules(), key=lambda x: x.title)): self.printer.emit_node(i, label=self.get_title(obj), shape="box") obj.fig_id = i
python
{ "resource": "" }
q269544
DiagramWriter.write_classes
test
def write_classes(self, diagram): """write a class diagram""" # sorted to get predictable (hence testable) results for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)): self.printer.emit_node(i, **self.get_values(obj)) obj.fig_id = i # inheritance links for rel in diagram.get_relationships("specialization"): self.printer.emit_edge( rel.from_object.fig_id, rel.to_object.fig_id, **self.inh_edges ) # implementation links for rel in diagram.get_relationships("implements"): self.printer.emit_edge(
python
{ "resource": "" }
q269545
DotWriter.set_printer
test
def set_printer(self, file_name, basename): """initialize DotWriter and add options for layout. """ layout
python
{ "resource": "" }
q269546
VCGWriter.set_printer
test
def set_printer(self, file_name, basename): """initialize VCGWriter for a UML graph""" self.graph_file = open(file_name, "w+") self.printer = VCGPrinter(self.graph_file) self.printer.open_graph( title=basename, layoutalgorithm="dfs",
python
{ "resource": "" }
q269547
MessageDefinition.may_be_emitted
test
def may_be_emitted(self): """return True if message may be emitted using the current interpreter""" if self.minversion is not None and self.minversion > sys.version_info:
python
{ "resource": "" }
q269548
MessageDefinition.format_help
test
def format_help(self, checkerref=False): """return the help string for the given message id""" desc = self.descr if checkerref: desc += " This message belongs to the %s checker." % self.checker.name title = self.msg if self.symbol: msgid = "%s (%s)" % (self.symbol, self.msgid) else: msgid = self.msgid if self.minversion or self.maxversion: restr = [] if self.minversion: restr.append("< %s" % ".".join([str(n) for n in self.minversion])) if self.maxversion: restr.append(">= %s" % ".".join([str(n) for n in self.maxversion]))
python
{ "resource": "" }
q269549
_get_env
test
def _get_env(): """Extracts the environment PYTHONPATH and appends the current sys.path to those.""" env = dict(os.environ)
python
{ "resource": "" }
q269550
lint
test
def lint(filename, options=()): """Pylint the given file. When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylint will classify it as a failed import. To get around this, we traverse down the directory tree to find the root of the package this module is in. We then invoke pylint from this directory. Finally, we must correct the filenames in the output generated by pylint so Emacs doesn't become confused (it will expect just the original filename, while pylint may extend it with extra directories if we've traversed down the tree) """ # traverse downwards until we are out of a python package full_path = osp.abspath(filename) parent_path = osp.dirname(full_path)
python
{ "resource": "" }
q269551
py_run
test
def py_run(command_options="", return_std=False, stdout=None, stderr=None): """Run pylint from python ``command_options`` is a string containing ``pylint`` command line options; ``return_std`` (boolean) indicates return of created standard output and error (see below); ``stdout`` and ``stderr`` are 'file-like' objects in which standard output could be written. Calling agent is responsible for stdout/err management (creation, close). Default standard output and error are those from sys, or standalone ones (``subprocess.PIPE``) are used if they are not set and ``return_std``. If ``return_std`` is set to ``True``, this function returns a 2-uple containing standard output and error related to created process, as follows: ``(stdout, stderr)``. To silently run Pylint on a module, and get its standard output and error: >>> (pylint_stdout, pylint_stderr) = py_run( 'module_name.py', True) """ # Detect if we use Python as executable or not, else default to `python` executable = sys.executable if "python" in sys.executable else "python" # Create command line to
python
{ "resource": "" }
q269552
_get_cycles
test
def _get_cycles(graph_dict, path, visited, result, vertice): """recursive function doing the real work for get_cycles""" if vertice in path: cycle = [vertice] for node in path[::-1]: if node == vertice: break cycle.insert(0, node) # make a canonical representation start_from = min(cycle) index = cycle.index(start_from) cycle = cycle[index:] + cycle[0:index] # append it to result if not already in if cycle not in result: result.append(cycle)
python
{ "resource": "" }
q269553
DotBackend.get_source
test
def get_source(self): """returns self._source""" if self._source is None: self.emit("}\n")
python
{ "resource": "" }
q269554
DotBackend.generate
test
def generate(self, outputfile=None, dotfile=None, mapfile=None): """Generates a graph file. :param str outputfile: filename and path [defaults to graphname.png] :param str dotfile: filename and path [defaults to graphname.dot] :param str mapfile: filename and path :rtype: str :return: a path to the generated file """ import subprocess # introduced in py 2.4 name = self.graphname if not dotfile: # if 'outputfile' is a dot file use it as 'dotfile' if outputfile and outputfile.endswith(".dot"): dotfile = outputfile else: dotfile = "%s.dot" % name if outputfile is not None: storedir, _, target = target_info_from_filename(outputfile) if target != "dot": pdot, dot_sourcepath = tempfile.mkstemp(".dot", name) os.close(pdot) else: dot_sourcepath = osp.join(storedir, dotfile) else: target = "png" pdot, dot_sourcepath = tempfile.mkstemp(".dot", name) ppng, outputfile = tempfile.mkstemp(".png", name) os.close(pdot) os.close(ppng)
python
{ "resource": "" }
q269555
_rest_format_section
test
def _rest_format_section(stream, section, options, doc=None): """format an options section using as ReST formatted output""" if section: print("%s\n%s" % (section, "'" * len(section)), file=stream) if doc: print(normalize_text(doc, line_len=79, indent=""), file=stream) print(file=stream)
python
{ "resource": "" }
q269556
MessagesHandlerMixIn._register_by_id_managed_msg
test
def _register_by_id_managed_msg(self, msgid, line, is_disabled=True): """If the msgid is a numeric one, then register it to inform the user it could furnish instead a symbolic msgid.""" try: message_definitions = self.msgs_store.get_message_definitions(msgid) for message_definition in message_definitions: if msgid == message_definition.msgid: MessagesHandlerMixIn.__by_id_managed_msgs.append( (
python
{ "resource": "" }
q269557
MessagesHandlerMixIn.disable
test
def disable(self, msgid, scope="package", line=None, ignore_unknown=False): """don't output message of the given id""" self._set_msg_status(
python
{ "resource": "" }
q269558
MessagesHandlerMixIn.enable
test
def enable(self, msgid, scope="package", line=None, ignore_unknown=False): """reenable message of the given id""" self._set_msg_status( msgid, enable=True, scope=scope, line=line,
python
{ "resource": "" }
q269559
MessagesHandlerMixIn._message_symbol
test
def _message_symbol(self, msgid): """Get the message symbol of the given message id Return the original message id if the message does not exist. """ try:
python
{ "resource": "" }
q269560
MessagesHandlerMixIn.is_message_enabled
test
def is_message_enabled(self, msg_descr, line=None, confidence=None): """return true if the message associated to the given message id is enabled msgid may be either a numeric or symbolic message id. """ if self.config.confidence and confidence: if confidence.name not in self.config.confidence: return False try: message_definitions = self.msgs_store.get_message_definitions(msg_descr) msgids = [md.msgid for md in message_definitions] except UnknownMessageError: # The linter
python
{ "resource": "" }
q269561
MessagesHandlerMixIn.add_message
test
def add_message( self, msg_descr, line=None, node=None, args=None, confidence=UNDEFINED, col_offset=None, ): """Adds a message given by ID or name. If provided, the message string is expanded using args. AST checkers must provide the node argument (but may optionally provide line if the line number is different), raw and token checkers
python
{ "resource": "" }
q269562
MessagesHandlerMixIn.print_full_documentation
test
def print_full_documentation(self, stream=None): """output a full documentation in ReST format""" if not stream: stream = sys.stdout print("Pylint global options and switches", file=stream) print("----------------------------------", file=stream) print("", file=stream) print("Pylint provides global options and switches.", file=stream) print("", file=stream) by_checker = {} for checker in self.get_checkers(): if checker.name == "master": if checker.options: for section, options in checker.options_by_section(): if section is None: title = "General options" else: title = "%s options" % section.capitalize() print(title, file=stream) print("~" * len(title), file=stream) _rest_format_section(stream, None, options) print("", file=stream) else: name = checker.name try: by_checker[name]["options"] += checker.options_and_values() by_checker[name]["msgs"].update(checker.msgs) by_checker[name]["reports"] += checker.reports except KeyError: by_checker[name] = { "options": list(checker.options_and_values()), "msgs": dict(checker.msgs), "reports": list(checker.reports),
python
{ "resource": "" }
q269563
MessagesHandlerMixIn._print_checker_doc
test
def _print_checker_doc(checker_name, info, stream=None): """Helper method for print_full_documentation. Also used by doc/exts/pylint_extensions.py. """ if not stream: stream = sys.stdout doc = info.get("doc") module = info.get("module") msgs = info.get("msgs") options = info.get("options") reports = info.get("reports") checker_title = "%s checker" % (checker_name.replace("_", " ").title()) if module: # Provide anchor to link against print(".. _%s:\n" % module, file=stream) print(checker_title, file=stream) print("~" * len(checker_title), file=stream) print("", file=stream) if module: print("This checker is provided by ``%s``." % module, file=stream) print("Verbatim name of the checker is ``%s``." % checker_name, file=stream) print("", file=stream) if doc: # Provide anchor to link against title = "{} Documentation".format(checker_title) print(title, file=stream) print("^" * len(title), file=stream) print(cleandoc(doc), file=stream) print("", file=stream) if options: title = "{} Options".format(checker_title)
python
{ "resource": "" }
q269564
_get_indent_length
test
def _get_indent_length(line): """Return the length of the indentation on the given token's line.""" result = 0 for char in line: if char == " ": result += 1
python
{ "resource": "" }
q269565
_get_indent_hint_line
test
def _get_indent_hint_line(bar_positions, bad_position): """Return a line with |s for each of the positions in the given lists.""" if not bar_positions: return ("", "") # TODO tabs should not be replaced by some random (8) number of spaces bar_positions = [_get_indent_length(indent) for indent in bar_positions] bad_position = _get_indent_length(bad_position) delta_message = "" markers = [(pos, "|") for pos in bar_positions] if len(markers) == 1: # if we have only one marker we'll provide an extra hint on how to fix expected_position = markers[0][0] delta = abs(expected_position - bad_position) direction = "add" if expected_position >
python
{ "resource": "" }
q269566
TokenWrapper.token_indent
test
def token_indent(self, idx): """Get an indentation string for hanging indentation, consisting of the line-indent plus a number of spaces to fill up to the column of this token. e.g. the token indent for foo in "<TAB><TAB>print(foo)"
python
{ "resource": "" }
q269567
ContinuedLineState.handle_line_start
test
def handle_line_start(self, pos): """Record the first non-junk token at the start of a line.""" if self._line_start > -1: return check_token_position = pos if self._tokens.token(pos) == _ASYNC_TOKEN: check_token_position += 1
python
{ "resource": "" }
q269568
ContinuedLineState.get_valid_indentations
test
def get_valid_indentations(self, idx): """Returns the valid offsets for the token at the given position.""" # The closing brace on a dict or the 'for' in a dict comprehension may # reset two indent levels because the dict value is ended implicitly stack_top = -1 if ( self._tokens.token(idx) in ("}", "for") and self._cont_stack[-1].token == ":" ): stack_top = -2 indent
python
{ "resource": "" }
q269569
ContinuedLineState._hanging_indent_after_bracket
test
def _hanging_indent_after_bracket(self, bracket, position): """Extracts indentation information for a hanging indent Case of hanging indent after a bracket (including parenthesis) :param str bracket: bracket in question :param int position: Position of bracket in self._tokens :returns: the state and valid positions for hanging indentation :rtype: _ContinuedIndent """ indentation = self._tokens.line_indent(position) if ( self._is_block_opener and self._continuation_string == self._block_indent_string ): return _ContinuedIndent( HANGING_BLOCK, bracket, position, _Indentations(indentation + self._continuation_string, indentation), _BeforeBlockIndentations( indentation + self._continuation_string, indentation + self._continuation_string * 2, ), ) if bracket == ":": # If the dict key was on the same line as the open brace, the new # correct indent should be relative to the key instead of the
python
{ "resource": "" }
q269570
ContinuedLineState._continuation_inside_bracket
test
def _continuation_inside_bracket(self, bracket, position): """Extracts indentation information for a continued indent.""" indentation = self._tokens.line_indent(position) token_indent = self._tokens.token_indent(position) next_token_indent = self._tokens.token_indent(position + 1) if ( self._is_block_opener and next_token_indent == indentation + self._block_indent_string
python
{ "resource": "" }
q269571
ContinuedLineState.push_token
test
def push_token(self, token, position): """Pushes a new token for continued indentation on the stack. Tokens that can modify continued indentation offsets are: * opening brackets * 'lambda' * : inside dictionaries push_token relies on the caller to filter out
python
{ "resource": "" }
q269572
FormatChecker.new_line
test
def new_line(self, tokens, line_end, line_start): """a new line has been encountered, process it if necessary""" if _last_token_on_line_is(tokens, line_end, ";"): self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end)) line_num = tokens.start_line(line_start)
python
{ "resource": "" }
q269573
FormatChecker._check_keyword_parentheses
test
def _check_keyword_parentheses(self, tokens, start): """Check that there are not unnecessary parens after a keyword. Parens are unnecessary if there is exactly one balanced outer pair on a line, and it is followed by a colon, and contains no commas (i.e. is not a tuple). Args: tokens: list of Tokens; the entire list of Tokens. start: int; the position of the keyword in the token list. """ # If the next token is not a paren, we're fine. if self._inside_brackets(":") and tokens[start][1] == "for": self._pop_token() if tokens[start + 1][1] != "(": return found_and_or = False depth = 0 keyword_token = str(tokens[start][1]) line_num = tokens[start][2][0] for i in range(start, len(tokens) - 1): token = tokens[i] # If we hit a newline, then assume any parens were for continuation. if token[0] == tokenize.NL: return if token[1] == "(": depth += 1 elif token[1] == ")": depth -= 1 if depth: continue # ')' can't happen after if (foo), since it would be a syntax error. if tokens[i + 1][1] in (":", ")", "]", "}", "in") or tokens[i + 1][ 0 ] in (tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT): # The empty tuple () is always accepted. if i == start + 2: return if keyword_token == "not": if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token )
python
{ "resource": "" }
q269574
FormatChecker._has_valid_type_annotation
test
def _has_valid_type_annotation(self, tokens, i): """Extended check of PEP-484 type hint presence""" if not self._inside_brackets("("): return False # token_info # type string start end line # 0 1 2 3 4 bracket_level = 0 for token in tokens[i - 1 :: -1]: if token[1] == ":":
python
{ "resource": "" }
q269575
FormatChecker._check_equals_spacing
test
def _check_equals_spacing(self, tokens, i): """Check the spacing of a single equals sign.""" if self._has_valid_type_annotation(tokens, i): self._check_space(tokens, i, (_MUST, _MUST)) elif self._inside_brackets("(") or self._inside_brackets("lambda"):
python
{ "resource": "" }
q269576
FormatChecker._check_surrounded_by_space
test
def _check_surrounded_by_space(self, tokens, i): """Check that a
python
{ "resource": "" }
q269577
FormatChecker.visit_default
test
def visit_default(self, node): """check the node line number and check it if not yet done""" if not node.is_statement: return if not node.root().pure_python: return # XXX block visit of child nodes prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno else: # The line on which a finally: occurs in a try/finally # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: if ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 else: prev_line = node.parent.statement().fromlineno line = node.fromlineno assert line, node
python
{ "resource": "" }
q269578
FormatChecker._check_multi_statement_line
test
def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If)
python
{ "resource": "" }
q269579
FormatChecker.check_lines
test
def check_lines(self, lines, i): """check lines have less than a maximum number of characters """ max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines def check_line(line, i): if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) else: # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if not stripped_line and _EMPTY_LINE in self.config.no_space_check: # allow empty lines pass elif line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) # Don't count excess whitespace in the line length.
python
{ "resource": "" }
q269580
FormatChecker.check_indent_level
test
def check_indent_level(self, string, expected, line_num): """return the indent level of the string """ indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": if string[0] != indent[0]: if string[0] == "\t": args = ("tab", "space") else: args = ("space", "tab") self.add_message("mixed-indentation", args=args, line=line_num) return level
python
{ "resource": "" }
q269581
_in_iterating_context
test
def _in_iterating_context(node): """Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context(). """ parent = node.parent # Since a call can't be the loop variant we only need to know if the node's # parent is a 'for' loop to know it's being used as the iterator for the # loop. if isinstance(parent, astroid.For): return True # Need to make sure the use of the node is in the iterator part of the # comprehension. if isinstance(parent, astroid.Comprehension): if parent.iter == node: return True # Various built-ins can take in an iterable or list and lead to the same # value. elif isinstance(parent, astroid.Call): if isinstance(parent.func, astroid.Name): parent_scope = parent.func.lookup(parent.func.name)[0] if _is_builtin(parent_scope) and parent.func.name in _ACCEPTS_ITERATOR: return True elif isinstance(parent.func, astroid.Attribute): if parent.func.attrname in ATTRIBUTES_ACCEPTS_ITERATOR: return True inferred = utils.safe_infer(parent.func) if inferred: if inferred.qname() in _BUILTIN_METHOD_ACCEPTS_ITERATOR: return True
python
{ "resource": "" }
q269582
_is_conditional_import
test
def _is_conditional_import(node): """Checks if an import node is in the context of a conditional. """ parent = node.parent return isinstance(
python
{ "resource": "" }
q269583
Python3Checker.visit_name
test
def visit_name(self, node): """Detect when a "bad" built-in is referenced.""" found_node, _ = node.lookup(node.name) if not _is_builtin(found_node): return if node.name not in self._bad_builtins: return if node_ignores_exception(node) or isinstance(
python
{ "resource": "" }
q269584
Python3Checker.visit_subscript
test
def visit_subscript(self, node): """ Look for indexing exceptions. """ try: for inferred in node.value.infer(): if not isinstance(inferred, astroid.Instance): continue
python
{ "resource": "" }
q269585
Python3Checker.visit_attribute
test
def visit_attribute(self, node): """Look for removed attributes""" if node.attrname == "xreadlines": self.add_message("xreadlines-attribute", node=node) return exception_message = "message" try: for inferred in node.expr.infer(): if isinstance(inferred, astroid.Instance) and utils.inherit_from_std_ex( inferred ): if node.attrname == exception_message: # Exceptions with .message clearly defined are an exception if exception_message in inferred.instance_attrs: continue
python
{ "resource": "" }
q269586
Python3Checker.visit_excepthandler
test
def visit_excepthandler(self, node): """Visit an except handler block and check for exception unpacking.""" def _is_used_in_except_block(node): scope = node.scope() current = node while ( current and current != scope and not isinstance(current, astroid.ExceptHandler) ): current = current.parent return isinstance(current, astroid.ExceptHandler) and current.type != node if isinstance(node.name, (astroid.Tuple, astroid.List)): self.add_message("unpacking-in-except", node=node) return if not node.name: return # Find any names scope = node.parent.scope() scope_names = scope.nodes_of_class(astroid.Name, skip_klass=astroid.FunctionDef) scope_names = list(scope_names) potential_leaked_names = [ scope_name for scope_name in scope_names if scope_name.name == node.name.name and scope_name.lineno > node.lineno and not
python
{ "resource": "" }
q269587
Python3Checker.visit_raise
test
def visit_raise(self, node): """Visit a raise statement and check for raising strings or old-raise-syntax. """ # Ignore empty raise. if node.exc is None:
python
{ "resource": "" }
q269588
find_pylintrc
test
def find_pylintrc(): """search the pylint rc file and return its path if it find it, else None """ # is there a pylint rc file in the current directory ? if os.path.exists("pylintrc"): return os.path.abspath("pylintrc") if os.path.exists(".pylintrc"): return os.path.abspath(".pylintrc") if os.path.isfile("__init__.py"): curdir = os.path.abspath(os.getcwd()) while os.path.isfile(os.path.join(curdir, "__init__.py")): curdir = os.path.abspath(os.path.join(curdir, "..")) if os.path.isfile(os.path.join(curdir, "pylintrc")): return os.path.join(curdir, "pylintrc") if os.path.isfile(os.path.join(curdir, ".pylintrc")): return os.path.join(curdir, ".pylintrc") if "PYLINTRC" in os.environ and os.path.exists(os.environ["PYLINTRC"]): pylintrc
python
{ "resource": "" }
q269589
_validate
test
def _validate(value, optdict, name=""): """return a validated value for an option according to its type optional argument name is only used
python
{ "resource": "" }
q269590
_expand_default
test
def _expand_default(self, option): """Patch OptionParser.expand_default with custom behaviour This will handle defaults to avoid overriding values in the configuration file. """ if self.parser is None or not self.default_tag: return option.help optname = option._long_opts[0][2:] try: provider = self.parser.options_manager._all_options[optname] except KeyError: value = None else: optdict =
python
{ "resource": "" }
q269591
OptionParser._match_long_opt
test
def _match_long_opt(self, opt): """Disable abbreviations.""" if opt not in self._long_opt:
python
{ "resource": "" }
q269592
OptionsManagerMixIn.register_options_provider
test
def register_options_provider(self, provider, own_group=True): """register an options provider""" assert provider.priority <= 0, "provider's priority can't be >= 0" for i in range(len(self.options_providers)): if provider.priority > self.options_providers[i].priority: self.options_providers.insert(i, provider) break else: self.options_providers.append(provider) non_group_spec_options = [ option for option in provider.options if "group" not in option[1] ] groups = getattr(provider, "option_groups", ()) if own_group and non_group_spec_options: self.add_option_group( provider.name.upper(), provider.__doc__, non_group_spec_options, provider, ) else:
python
{ "resource": "" }
q269593
OptionsManagerMixIn.cb_set_provider_option
test
def cb_set_provider_option(self, option, opt, value, parser): """optik callback for option setting""" if opt.startswith("--"): # remove -- on long option opt = opt[2:] else: # short option, get its long equivalent
python
{ "resource": "" }
q269594
OptionsManagerMixIn.global_set_option
test
def global_set_option(self, opt, value): """set option on the correct option provider"""
python
{ "resource": "" }
q269595
OptionsManagerMixIn.generate_config
test
def generate_config(self, stream=None, skipsections=(), encoding=None): """write a configuration file according to the current configuration into the given stream or stdout """ options_by_section = {} sections = [] for provider in self.options_providers: for section, options in provider.options_by_section(): if section is None: section = provider.name if section in skipsections: continue options = [ (n, d, v) for (n, d, v) in options if d.get("type") is not None and not d.get("deprecated") ] if not options:
python
{ "resource": "" }
q269596
OptionsManagerMixIn.load_config_file
test
def load_config_file(self): """dispatch values previously read from a configuration file to each options provider) """ parser = self.cfgfile_parser for section in parser.sections():
python
{ "resource": "" }
q269597
OptionsManagerMixIn.load_command_line_configuration
test
def load_command_line_configuration(self, args=None): """Override configuration according to command line parameters return additional arguments """ with _patch_optparse(): if args is None: args = sys.argv[1:] else: args = list(args) (options, args) = self.cmdline_parser.parse_args(args=args) for provider in self._nocallback_options: config = provider.config
python
{ "resource": "" }
q269598
OptionsManagerMixIn.add_help_section
test
def add_help_section(self, title, description, level=0): """add a dummy option section for help purpose """ group = optparse.OptionGroup(
python
{ "resource": "" }
q269599
OptionsManagerMixIn.help
test
def help(self, level=0): """return the usage string for available options """ self.cmdline_parser.formatter.output_level = level
python
{ "resource": "" }