partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
ClassChecker._check_classmethod_declaration
Checks for uses of classmethod() or staticmethod() When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node.
pylint/checkers/classes.py
def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod() When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, astroid.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, astroid.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, astroid.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, astroid.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0])
def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod() When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belongs to the class where it is defined. `node` is an assign node. """ if not isinstance(node.value, astroid.Call): return # check the function called is "classmethod" or "staticmethod" func = node.value.func if not isinstance(func, astroid.Name) or func.name not in ( "classmethod", "staticmethod", ): return msg = ( "no-classmethod-decorator" if func.name == "classmethod" else "no-staticmethod-decorator" ) # assignment must be at a class scope parent_class = node.scope() if not isinstance(parent_class, astroid.ClassDef): return # Check if the arg passed to classmethod is a class member classmeth_arg = node.value.args[0] if not isinstance(classmeth_arg, astroid.Name): return method_name = classmeth_arg.name if any(method_name == member.name for member in parent_class.mymethods()): self.add_message(msg, node=node.targets[0])
[ "Checks", "for", "uses", "of", "classmethod", "()", "or", "staticmethod", "()" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1202-L1239
[ "def", "_check_classmethod_declaration", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ".", "value", ",", "astroid", ".", "Call", ")", ":", "return", "# check the function called is \"classmethod\" or \"staticmethod\"", "func", "=", "node", ".", "value", ".", "func", "if", "not", "isinstance", "(", "func", ",", "astroid", ".", "Name", ")", "or", "func", ".", "name", "not", "in", "(", "\"classmethod\"", ",", "\"staticmethod\"", ",", ")", ":", "return", "msg", "=", "(", "\"no-classmethod-decorator\"", "if", "func", ".", "name", "==", "\"classmethod\"", "else", "\"no-staticmethod-decorator\"", ")", "# assignment must be at a class scope", "parent_class", "=", "node", ".", "scope", "(", ")", "if", "not", "isinstance", "(", "parent_class", ",", "astroid", ".", "ClassDef", ")", ":", "return", "# Check if the arg passed to classmethod is a class member", "classmeth_arg", "=", "node", ".", "value", ".", "args", "[", "0", "]", "if", "not", "isinstance", "(", "classmeth_arg", ",", "astroid", ".", "Name", ")", ":", "return", "method_name", "=", "classmeth_arg", ".", "name", "if", "any", "(", "method_name", "==", "member", ".", "name", "for", "member", "in", "parent_class", ".", "mymethods", "(", ")", ")", ":", "self", ".", "add_message", "(", "msg", ",", "node", "=", "node", ".", "targets", "[", "0", "]", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_protected_attribute_access
Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass.
pylint/checkers/classes.py
def _check_protected_attribute_access(self, node): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # XXX infer to be more safe and less dirty ?? # in classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, astroid.Call) and isinstance(node.expr.func, astroid.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (callee == klass.name or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement() if ( isinstance(stmt, astroid.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], astroid.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return self.add_message("protected-access", node=node, args=attrname)
def _check_protected_attribute_access(self, node): """Given an attribute access node (set or get), check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self._attr in a method or cls._attr in a classmethod. Checked by _check_first_attr. * Klass._attr inside "Klass" class. * Klass2._attr inside "Klass" class when Klass2 is a base class of Klass. """ attrname = node.attrname if ( is_attr_protected(attrname) and attrname not in self.config.exclude_protected ): klass = node_frame_class(node) # XXX infer to be more safe and less dirty ?? # in classes, check we are not getting a parent method # through the class object or through super callee = node.expr.as_string() # We are not in a class, no remaining valid case if klass is None: self.add_message("protected-access", node=node, args=attrname) return # If the expression begins with a call to super, that's ok. if ( isinstance(node.expr, astroid.Call) and isinstance(node.expr.func, astroid.Name) and node.expr.func.name == "super" ): return # If the expression begins with a call to type(self), that's ok. if self._is_type_self_call(node.expr): return # We are in a class, one remaining valid cases, Klass._attr inside # Klass if not (callee == klass.name or callee in klass.basenames): # Detect property assignments in the body of the class. # This is acceptable: # # class A: # b = property(lambda: self._b) stmt = node.parent.statement() if ( isinstance(stmt, astroid.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], astroid.AssignName) ): name = stmt.targets[0].name if _is_attribute_property(name, klass): return self.add_message("protected-access", node=node, args=attrname)
[ "Given", "an", "attribute", "access", "node", "(", "set", "or", "get", ")", "check", "if", "attribute", "access", "is", "legitimate", ".", "Call", "_check_first_attr", "with", "node", "before", "calling", "this", "method", ".", "Valid", "cases", "are", ":", "*", "self", ".", "_attr", "in", "a", "method", "or", "cls", ".", "_attr", "in", "a", "classmethod", ".", "Checked", "by", "_check_first_attr", ".", "*", "Klass", ".", "_attr", "inside", "Klass", "class", ".", "*", "Klass2", ".", "_attr", "inside", "Klass", "class", "when", "Klass2", "is", "a", "base", "class", "of", "Klass", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1241-L1301
[ "def", "_check_protected_attribute_access", "(", "self", ",", "node", ")", ":", "attrname", "=", "node", ".", "attrname", "if", "(", "is_attr_protected", "(", "attrname", ")", "and", "attrname", "not", "in", "self", ".", "config", ".", "exclude_protected", ")", ":", "klass", "=", "node_frame_class", "(", "node", ")", "# XXX infer to be more safe and less dirty ??", "# in classes, check we are not getting a parent method", "# through the class object or through super", "callee", "=", "node", ".", "expr", ".", "as_string", "(", ")", "# We are not in a class, no remaining valid case", "if", "klass", "is", "None", ":", "self", ".", "add_message", "(", "\"protected-access\"", ",", "node", "=", "node", ",", "args", "=", "attrname", ")", "return", "# If the expression begins with a call to super, that's ok.", "if", "(", "isinstance", "(", "node", ".", "expr", ",", "astroid", ".", "Call", ")", "and", "isinstance", "(", "node", ".", "expr", ".", "func", ",", "astroid", ".", "Name", ")", "and", "node", ".", "expr", ".", "func", ".", "name", "==", "\"super\"", ")", ":", "return", "# If the expression begins with a call to type(self), that's ok.", "if", "self", ".", "_is_type_self_call", "(", "node", ".", "expr", ")", ":", "return", "# We are in a class, one remaining valid cases, Klass._attr inside", "# Klass", "if", "not", "(", "callee", "==", "klass", ".", "name", "or", "callee", "in", "klass", ".", "basenames", ")", ":", "# Detect property assignments in the body of the class.", "# This is acceptable:", "#", "# class A:", "# b = property(lambda: self._b)", "stmt", "=", "node", ".", "parent", ".", "statement", "(", ")", "if", "(", "isinstance", "(", "stmt", ",", "astroid", ".", "Assign", ")", "and", "len", "(", "stmt", ".", "targets", ")", "==", "1", "and", "isinstance", "(", "stmt", ".", "targets", "[", "0", "]", ",", "astroid", ".", "AssignName", ")", ")", ":", "name", "=", "stmt", ".", "targets", "[", "0", "]", ".", "name", "if", "_is_attribute_property", "(", "name", ",", "klass", ")", ":", "return", "self", ".", "add_message", "(", "\"protected-access\"", ",", "node", "=", "node", ",", "args", "=", "attrname", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker.visit_name
check if the name handle an access to a class member if so, register it
pylint/checkers/classes.py
def visit_name(self, node): """check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = False
def visit_name(self, node): """check if the name handle an access to a class member if so, register it """ if self._first_attrs and ( node.name == self._first_attrs[-1] or not self._first_attrs[-1] ): self._meth_could_be_func = False
[ "check", "if", "the", "name", "handle", "an", "access", "to", "a", "class", "member", "if", "so", "register", "it" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1312-L1319
[ "def", "visit_name", "(", "self", ",", "node", ")", ":", "if", "self", ".", "_first_attrs", "and", "(", "node", ".", "name", "==", "self", ".", "_first_attrs", "[", "-", "1", "]", "or", "not", "self", ".", "_first_attrs", "[", "-", "1", "]", ")", ":", "self", ".", "_meth_could_be_func", "=", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_accessed_members
check that accessed members are defined
pylint/checkers/classes.py
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 ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame() lno = defstmt.fromlineno for _node in nodes: if ( _node.frame() is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), )
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 ] # if there are still more than one, don't attempt to be smarter # than we can be if len(defstmts) == 1: defstmt = defstmts[0] # check that if the node is accessed in the same method as # it's defined, it's accessed after the initial assignment frame = defstmt.frame() lno = defstmt.fromlineno for _node in nodes: if ( _node.frame() is frame and _node.fromlineno < lno and not astroid.are_exclusive( _node.statement(), defstmt, excs ) ): self.add_message( "access-member-before-definition", node=_node, args=(attr, lno), )
[ "check", "that", "accessed", "members", "are", "defined" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1321-L1380
[ "def", "_check_accessed_members", "(", "self", ",", "node", ",", "accessed", ")", ":", "# 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", "]", "# if there are still more than one, don't attempt to be smarter", "# than we can be", "if", "len", "(", "defstmts", ")", "==", "1", ":", "defstmt", "=", "defstmts", "[", "0", "]", "# check that if the node is accessed in the same method as", "# it's defined, it's accessed after the initial assignment", "frame", "=", "defstmt", ".", "frame", "(", ")", "lno", "=", "defstmt", ".", "fromlineno", "for", "_node", "in", "nodes", ":", "if", "(", "_node", ".", "frame", "(", ")", "is", "frame", "and", "_node", ".", "fromlineno", "<", "lno", "and", "not", "astroid", ".", "are_exclusive", "(", "_node", ".", "statement", "(", ")", ",", "defstmt", ",", "excs", ")", ")", ":", "self", ".", "add_message", "(", "\"access-member-before-definition\"", ",", "node", "=", "_node", ",", "args", "=", "(", "attr", ",", "lno", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_first_arg_for_type
check the name of first argument, expect: * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method
pylint/checkers/classes.py
def _check_first_arg_for_type(self, node, metaclass=0): """check the name of first argument, expect: * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return first_arg = node.args.args and node.argnames()[0] self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class else: # class method if node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node)
def _check_first_arg_for_type(self, node, metaclass=0): """check the name of first argument, expect: * 'self' for a regular method * 'cls' for a class method or a metaclass regular method (actually valid-classmethod-first-arg value) * 'mcs' for a metaclass class method (actually valid-metaclass-classmethod-first-arg) * not one of the above for a static method """ # don't care about functions with unknown argument (builtins) if node.args.args is None: return first_arg = node.args.args and node.argnames()[0] self._first_attrs.append(first_arg) first = self._first_attrs[-1] # static method if node.type == "staticmethod": if ( first_arg == "self" or first_arg in self.config.valid_classmethod_first_arg or first_arg in self.config.valid_metaclass_classmethod_first_arg ): self.add_message("bad-staticmethod-argument", args=first, node=node) return self._first_attrs[-1] = None # class / regular method with no args elif not node.args.args: self.add_message("no-method-argument", node=node) # metaclass elif metaclass: # metaclass __new__ or classmethod if node.type == "classmethod": self._check_first_arg_config( first, self.config.valid_metaclass_classmethod_first_arg, node, "bad-mcs-classmethod-argument", node.name, ) # metaclass regular method else: self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-mcs-method-argument", node.name, ) # regular class else: # class method if node.type == "classmethod" or node.name == "__class_getitem__": self._check_first_arg_config( first, self.config.valid_classmethod_first_arg, node, "bad-classmethod-argument", node.name, ) # regular method without self as argument elif first != "self": self.add_message("no-self-argument", node=node)
[ "check", "the", "name", "of", "first", "argument", "expect", ":" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1382-L1444
[ "def", "_check_first_arg_for_type", "(", "self", ",", "node", ",", "metaclass", "=", "0", ")", ":", "# don't care about functions with unknown argument (builtins)", "if", "node", ".", "args", ".", "args", "is", "None", ":", "return", "first_arg", "=", "node", ".", "args", ".", "args", "and", "node", ".", "argnames", "(", ")", "[", "0", "]", "self", ".", "_first_attrs", ".", "append", "(", "first_arg", ")", "first", "=", "self", ".", "_first_attrs", "[", "-", "1", "]", "# static method", "if", "node", ".", "type", "==", "\"staticmethod\"", ":", "if", "(", "first_arg", "==", "\"self\"", "or", "first_arg", "in", "self", ".", "config", ".", "valid_classmethod_first_arg", "or", "first_arg", "in", "self", ".", "config", ".", "valid_metaclass_classmethod_first_arg", ")", ":", "self", ".", "add_message", "(", "\"bad-staticmethod-argument\"", ",", "args", "=", "first", ",", "node", "=", "node", ")", "return", "self", ".", "_first_attrs", "[", "-", "1", "]", "=", "None", "# class / regular method with no args", "elif", "not", "node", ".", "args", ".", "args", ":", "self", ".", "add_message", "(", "\"no-method-argument\"", ",", "node", "=", "node", ")", "# metaclass", "elif", "metaclass", ":", "# metaclass __new__ or classmethod", "if", "node", ".", "type", "==", "\"classmethod\"", ":", "self", ".", "_check_first_arg_config", "(", "first", ",", "self", ".", "config", ".", "valid_metaclass_classmethod_first_arg", ",", "node", ",", "\"bad-mcs-classmethod-argument\"", ",", "node", ".", "name", ",", ")", "# metaclass regular method", "else", ":", "self", ".", "_check_first_arg_config", "(", "first", ",", "self", ".", "config", ".", "valid_classmethod_first_arg", ",", "node", ",", "\"bad-mcs-method-argument\"", ",", "node", ".", "name", ",", ")", "# regular class", "else", ":", "# class method", "if", "node", ".", "type", "==", "\"classmethod\"", "or", "node", ".", "name", "==", "\"__class_getitem__\"", ":", "self", ".", "_check_first_arg_config", "(", "first", ",", "self", ".", "config", ".", "valid_classmethod_first_arg", ",", "node", ",", "\"bad-classmethod-argument\"", ",", "node", ".", "name", ",", ")", "# regular method without self as argument", "elif", "first", "!=", "\"self\"", ":", "self", ".", "add_message", "(", "\"no-self-argument\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_bases_classes
check that the given class node implements abstract methods from base classes
pylint/checkers/classes.py
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: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name))
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: continue # owner is not this class, it must be a parent class # check that the ancestor's method is not abstract if name in node.locals: # it is redefined as an attribute or with a descriptor continue self.add_message("abstract-method", node=node, args=(name, owner.name))
[ "check", "that", "the", "given", "class", "node", "implements", "abstract", "methods", "from", "base", "classes" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1455-L1480
[ "def", "_check_bases_classes", "(", "self", ",", "node", ")", ":", "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", ":", "continue", "# owner is not this class, it must be a parent class", "# check that the ancestor's method is not abstract", "if", "name", "in", "node", ".", "locals", ":", "# it is redefined as an attribute or with a descriptor", "continue", "self", ".", "add_message", "(", "\"abstract-method\"", ",", "node", "=", "node", ",", "args", "=", "(", "name", ",", "owner", ".", "name", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_init
check that the __init__ method call super or ancestors'__init__ method
pylint/checkers/classes.py
def _check_init(self, node): """check that the __init__ method call super or ancestors'__init__ method """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return klass_node = node.parent.frame() to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) for stmt in node.nodes_of_class(astroid.Call): expr = stmt.func if not isinstance(expr, astroid.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, astroid.Call) and isinstance(expr.expr.func, astroid.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The infered klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, astroid.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, objects.Super): return try: del not_called_yet[klass] except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message("super-init-not-called", args=klass.name, node=node)
def _check_init(self, node): """check that the __init__ method call super or ancestors'__init__ method """ if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return klass_node = node.parent.frame() to_call = _ancestors_to_call(klass_node) not_called_yet = dict(to_call) for stmt in node.nodes_of_class(astroid.Call): expr = stmt.func if not isinstance(expr, astroid.Attribute) or expr.attrname != "__init__": continue # skip the test if using super if ( isinstance(expr.expr, astroid.Call) and isinstance(expr.expr.func, astroid.Name) and expr.expr.func.name == "super" ): return try: for klass in expr.expr.infer(): if klass is astroid.Uninferable: continue # The infered klass can be super(), which was # assigned to a variable and the `__init__` # was called later. # # base = super() # base.__init__(...) if ( isinstance(klass, astroid.Instance) and isinstance(klass._proxied, astroid.ClassDef) and is_builtin_object(klass._proxied) and klass._proxied.name == "super" ): return if isinstance(klass, objects.Super): return try: del not_called_yet[klass] except KeyError: if klass not in to_call: self.add_message( "non-parent-init-called", node=expr, args=klass.name ) except astroid.InferenceError: continue for klass, method in not_called_yet.items(): cls = node_frame_class(method) if klass.name == "object" or (cls and cls.name == "object"): continue self.add_message("super-init-not-called", args=klass.name, node=node)
[ "check", "that", "the", "__init__", "method", "call", "super", "or", "ancestors", "__init__", "method" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1482-L1537
[ "def", "_check_init", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "linter", ".", "is_message_enabled", "(", "\"super-init-not-called\"", ")", "and", "not", "self", ".", "linter", ".", "is_message_enabled", "(", "\"non-parent-init-called\"", ")", ":", "return", "klass_node", "=", "node", ".", "parent", ".", "frame", "(", ")", "to_call", "=", "_ancestors_to_call", "(", "klass_node", ")", "not_called_yet", "=", "dict", "(", "to_call", ")", "for", "stmt", "in", "node", ".", "nodes_of_class", "(", "astroid", ".", "Call", ")", ":", "expr", "=", "stmt", ".", "func", "if", "not", "isinstance", "(", "expr", ",", "astroid", ".", "Attribute", ")", "or", "expr", ".", "attrname", "!=", "\"__init__\"", ":", "continue", "# skip the test if using super", "if", "(", "isinstance", "(", "expr", ".", "expr", ",", "astroid", ".", "Call", ")", "and", "isinstance", "(", "expr", ".", "expr", ".", "func", ",", "astroid", ".", "Name", ")", "and", "expr", ".", "expr", ".", "func", ".", "name", "==", "\"super\"", ")", ":", "return", "try", ":", "for", "klass", "in", "expr", ".", "expr", ".", "infer", "(", ")", ":", "if", "klass", "is", "astroid", ".", "Uninferable", ":", "continue", "# The infered klass can be super(), which was", "# assigned to a variable and the `__init__`", "# was called later.", "#", "# base = super()", "# base.__init__(...)", "if", "(", "isinstance", "(", "klass", ",", "astroid", ".", "Instance", ")", "and", "isinstance", "(", "klass", ".", "_proxied", ",", "astroid", ".", "ClassDef", ")", "and", "is_builtin_object", "(", "klass", ".", "_proxied", ")", "and", "klass", ".", "_proxied", ".", "name", "==", "\"super\"", ")", ":", "return", "if", "isinstance", "(", "klass", ",", "objects", ".", "Super", ")", ":", "return", "try", ":", "del", "not_called_yet", "[", "klass", "]", "except", "KeyError", ":", "if", "klass", "not", "in", "to_call", ":", "self", ".", "add_message", "(", "\"non-parent-init-called\"", ",", "node", "=", "expr", ",", "args", "=", "klass", ".", "name", ")", "except", "astroid", ".", "InferenceError", ":", "continue", "for", "klass", ",", "method", "in", "not_called_yet", ".", "items", "(", ")", ":", "cls", "=", "node_frame_class", "(", "method", ")", "if", "klass", ".", "name", "==", "\"object\"", "or", "(", "cls", "and", "cls", ".", "name", "==", "\"object\"", ")", ":", "continue", "self", ".", "add_message", "(", "\"super-init-not-called\"", ",", "args", "=", "klass", ".", "name", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._check_signature
check that the signature of the two given methods match
pylint/checkers/classes.py
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 ( isinstance(decorator, astroid.Attribute) and decorator.attrname == "setter" ): return if _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ): self.add_message( "arguments-differ", args=(class_type, method1.name), node=method1 ) elif len(method1.args.defaults) < len(refmethod.args.defaults): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 )
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 ( isinstance(decorator, astroid.Attribute) and decorator.attrname == "setter" ): return if _different_parameters( refmethod, method1, dummy_parameter_regex=self._dummy_rgx ): self.add_message( "arguments-differ", args=(class_type, method1.name), node=method1 ) elif len(method1.args.defaults) < len(refmethod.args.defaults): self.add_message( "signature-differs", args=(class_type, method1.name), node=method1 )
[ "check", "that", "the", "signature", "of", "the", "two", "given", "methods", "match" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1539-L1581
[ "def", "_check_signature", "(", "self", ",", "method1", ",", "refmethod", ",", "class_type", ",", "cls", ")", ":", "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", "(", "isinstance", "(", "decorator", ",", "astroid", ".", "Attribute", ")", "and", "decorator", ".", "attrname", "==", "\"setter\"", ")", ":", "return", "if", "_different_parameters", "(", "refmethod", ",", "method1", ",", "dummy_parameter_regex", "=", "self", ".", "_dummy_rgx", ")", ":", "self", ".", "add_message", "(", "\"arguments-differ\"", ",", "args", "=", "(", "class_type", ",", "method1", ".", "name", ")", ",", "node", "=", "method1", ")", "elif", "len", "(", "method1", ".", "args", ".", "defaults", ")", "<", "len", "(", "refmethod", ".", "args", ".", "defaults", ")", ":", "self", ".", "add_message", "(", "\"signature-differs\"", ",", "args", "=", "(", "class_type", ",", "method1", ".", "name", ")", ",", "node", "=", "method1", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassChecker._is_mandatory_method_param
Check if astroid.Name corresponds to first attribute variable name Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
pylint/checkers/classes.py
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 ( self._first_attrs and isinstance(node, astroid.Name) and node.name == self._first_attrs[-1] )
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 ( self._first_attrs and isinstance(node, astroid.Name) and node.name == self._first_attrs[-1] )
[ "Check", "if", "astroid", ".", "Name", "corresponds", "to", "first", "attribute", "variable", "name" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L1590-L1599
[ "def", "_is_mandatory_method_param", "(", "self", ",", "node", ")", ":", "return", "(", "self", ".", "_first_attrs", "and", "isinstance", "(", "node", ",", "astroid", ".", "Name", ")", "and", "node", ".", "name", "==", "self", ".", "_first_attrs", "[", "-", "1", "]", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_annotated_unpack_infer
Recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements. Returns an iterator which yields tuples in the format ('original node', 'infered node').
pylint/checkers/exceptions.py
def _annotated_unpack_infer(stmt, context=None): """ Recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements. Returns an iterator which yields tuples in the format ('original node', 'infered node'). """ if isinstance(stmt, (astroid.List, astroid.Tuple)): for elt in stmt.elts: inferred = utils.safe_infer(elt) if inferred and inferred is not astroid.Uninferable: yield elt, inferred return for infered in stmt.infer(context): if infered is astroid.Uninferable: continue yield stmt, infered
def _annotated_unpack_infer(stmt, context=None): """ Recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements. Returns an iterator which yields tuples in the format ('original node', 'infered node'). """ if isinstance(stmt, (astroid.List, astroid.Tuple)): for elt in stmt.elts: inferred = utils.safe_infer(elt) if inferred and inferred is not astroid.Uninferable: yield elt, inferred return for infered in stmt.infer(context): if infered is astroid.Uninferable: continue yield stmt, infered
[ "Recursively", "generate", "nodes", "inferred", "by", "the", "given", "statement", ".", "If", "the", "inferred", "value", "is", "a", "list", "or", "a", "tuple", "recurse", "on", "the", "elements", ".", "Returns", "an", "iterator", "which", "yields", "tuples", "in", "the", "format", "(", "original", "node", "infered", "node", ")", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L45-L61
[ "def", "_annotated_unpack_infer", "(", "stmt", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "stmt", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ")", ")", ":", "for", "elt", "in", "stmt", ".", "elts", ":", "inferred", "=", "utils", ".", "safe_infer", "(", "elt", ")", "if", "inferred", "and", "inferred", "is", "not", "astroid", ".", "Uninferable", ":", "yield", "elt", ",", "inferred", "return", "for", "infered", "in", "stmt", ".", "infer", "(", "context", ")", ":", "if", "infered", "is", "astroid", ".", "Uninferable", ":", "continue", "yield", "stmt", ",", "infered" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_raising
Return true if the given statement node raise an exception
pylint/checkers/exceptions.py
def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body: if isinstance(node, astroid.Raise): return True return False
def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body: if isinstance(node, astroid.Raise): return True return False
[ "Return", "true", "if", "the", "given", "statement", "node", "raise", "an", "exception" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L64-L69
[ "def", "_is_raising", "(", "body", ":", "typing", ".", "List", ")", "->", "bool", ":", "for", "node", "in", "body", ":", "if", "isinstance", "(", "node", ",", "astroid", ".", "Raise", ")", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ExceptionsChecker._check_bad_exception_context
Verify that the exception context is properly set. An exception context can be only `None` or an exception.
pylint/checkers/exceptions.py
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): if cause.value is not None: self.add_message("bad-exception-context", node=node) elif not isinstance(cause, astroid.ClassDef) and not utils.inherit_from_std_ex( cause ): self.add_message("bad-exception-context", node=node)
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): if cause.value is not None: self.add_message("bad-exception-context", node=node) elif not isinstance(cause, astroid.ClassDef) and not utils.inherit_from_std_ex( cause ): self.add_message("bad-exception-context", node=node)
[ "Verify", "that", "the", "exception", "context", "is", "properly", "set", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L342-L357
[ "def", "_check_bad_exception_context", "(", "self", ",", "node", ")", ":", "cause", "=", "utils", ".", "safe_infer", "(", "node", ".", "cause", ")", "if", "cause", "in", "(", "astroid", ".", "Uninferable", ",", "None", ")", ":", "return", "if", "isinstance", "(", "cause", ",", "astroid", ".", "Const", ")", ":", "if", "cause", ".", "value", "is", "not", "None", ":", "self", ".", "add_message", "(", "\"bad-exception-context\"", ",", "node", "=", "node", ")", "elif", "not", "isinstance", "(", "cause", ",", "astroid", ".", "ClassDef", ")", "and", "not", "utils", ".", "inherit_from_std_ex", "(", "cause", ")", ":", "self", ".", "add_message", "(", "\"bad-exception-context\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ExceptionsChecker.visit_tryexcept
check for empty except
pylint/checkers/exceptions.py
def visit_tryexcept(self, node): """check for empty except""" self._check_try_except_raise(node) exceptions_classes = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, astroid.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: excs = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exc in excs: if exc is astroid.Uninferable: continue if isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex( exc ): # pylint: disable=protected-access exc = exc._proxied self._check_catching_non_exception(handler, exc, part) if not isinstance(exc, astroid.ClassDef): continue exc_ancestors = [ anc for anc in exc.ancestors() if isinstance(anc, astroid.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = "%s is an ancestor class of %s" % ( previous_exc.name, exc.name, ) self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exc.name in self.config.overgeneral_exceptions and exc.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exc.name, node=handler.type ) if exc in exceptions_classes: self.add_message( "duplicate-except", args=exc.name, node=handler.type ) exceptions_classes += [exc for _, exc in excs]
def visit_tryexcept(self, node): """check for empty except""" self._check_try_except_raise(node) exceptions_classes = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, astroid.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: excs = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exc in excs: if exc is astroid.Uninferable: continue if isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex( exc ): # pylint: disable=protected-access exc = exc._proxied self._check_catching_non_exception(handler, exc, part) if not isinstance(exc, astroid.ClassDef): continue exc_ancestors = [ anc for anc in exc.ancestors() if isinstance(anc, astroid.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = "%s is an ancestor class of %s" % ( previous_exc.name, exc.name, ) self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exc.name in self.config.overgeneral_exceptions and exc.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exc.name, node=handler.type ) if exc in exceptions_classes: self.add_message( "duplicate-except", args=exc.name, node=handler.type ) exceptions_classes += [exc for _, exc in excs]
[ "check", "for", "empty", "except" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L499-L568
[ "def", "visit_tryexcept", "(", "self", ",", "node", ")", ":", "self", ".", "_check_try_except_raise", "(", "node", ")", "exceptions_classes", "=", "[", "]", "nb_handlers", "=", "len", "(", "node", ".", "handlers", ")", "for", "index", ",", "handler", "in", "enumerate", "(", "node", ".", "handlers", ")", ":", "if", "handler", ".", "type", "is", "None", ":", "if", "not", "_is_raising", "(", "handler", ".", "body", ")", ":", "self", ".", "add_message", "(", "\"bare-except\"", ",", "node", "=", "handler", ")", "# check if an \"except:\" is followed by some other", "# except", "if", "index", "<", "(", "nb_handlers", "-", "1", ")", ":", "msg", "=", "\"empty except clause should always appear last\"", "self", ".", "add_message", "(", "\"bad-except-order\"", ",", "node", "=", "node", ",", "args", "=", "msg", ")", "elif", "isinstance", "(", "handler", ".", "type", ",", "astroid", ".", "BoolOp", ")", ":", "self", ".", "add_message", "(", "\"binary-op-exception\"", ",", "node", "=", "handler", ",", "args", "=", "handler", ".", "type", ".", "op", ")", "else", ":", "try", ":", "excs", "=", "list", "(", "_annotated_unpack_infer", "(", "handler", ".", "type", ")", ")", "except", "astroid", ".", "InferenceError", ":", "continue", "for", "part", ",", "exc", "in", "excs", ":", "if", "exc", "is", "astroid", ".", "Uninferable", ":", "continue", "if", "isinstance", "(", "exc", ",", "astroid", ".", "Instance", ")", "and", "utils", ".", "inherit_from_std_ex", "(", "exc", ")", ":", "# pylint: disable=protected-access", "exc", "=", "exc", ".", "_proxied", "self", ".", "_check_catching_non_exception", "(", "handler", ",", "exc", ",", "part", ")", "if", "not", "isinstance", "(", "exc", ",", "astroid", ".", "ClassDef", ")", ":", "continue", "exc_ancestors", "=", "[", "anc", "for", "anc", "in", "exc", ".", "ancestors", "(", ")", "if", "isinstance", "(", "anc", ",", "astroid", ".", "ClassDef", ")", "]", "for", "previous_exc", "in", "exceptions_classes", ":", "if", "previous_exc", "in", "exc_ancestors", ":", "msg", "=", "\"%s is an ancestor class of %s\"", "%", "(", "previous_exc", ".", "name", ",", "exc", ".", "name", ",", ")", "self", ".", "add_message", "(", "\"bad-except-order\"", ",", "node", "=", "handler", ".", "type", ",", "args", "=", "msg", ")", "if", "(", "exc", ".", "name", "in", "self", ".", "config", ".", "overgeneral_exceptions", "and", "exc", ".", "root", "(", ")", ".", "name", "==", "utils", ".", "EXCEPTIONS_MODULE", "and", "not", "_is_raising", "(", "handler", ".", "body", ")", ")", ":", "self", ".", "add_message", "(", "\"broad-except\"", ",", "args", "=", "exc", ".", "name", ",", "node", "=", "handler", ".", "type", ")", "if", "exc", "in", "exceptions_classes", ":", "self", ".", "add_message", "(", "\"duplicate-except\"", ",", "args", "=", "exc", ".", "name", ",", "node", "=", "handler", ".", "type", ")", "exceptions_classes", "+=", "[", "exc", "for", "_", ",", "exc", "in", "excs", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
NewStyleConflictChecker.visit_functiondef
check use of super
pylint/checkers/newstyle.py
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 if ( len(call.args) >= 2 and isinstance(call.args[1], astroid.Name) and call.args[1].name == "self" and isinstance(arg0, astroid.Attribute) and arg0.attrname == "__class__" ): self.add_message( "bad-super-call", node=call, args=("self.__class__",) ) continue try: supcls = call.args and next(call.args[0].infer(), None) except astroid.InferenceError: continue if klass is not supcls: name = None # if supcls is not Uninferable, then supcls was infered # and use its name. Otherwise, try to look # for call.args[0].name if supcls: name = supcls.name elif call.args and hasattr(call.args[0], "name"): name = call.args[0].name if name: self.add_message("bad-super-call", node=call, args=(name,))
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 if ( len(call.args) >= 2 and isinstance(call.args[1], astroid.Name) and call.args[1].name == "self" and isinstance(arg0, astroid.Attribute) and arg0.attrname == "__class__" ): self.add_message( "bad-super-call", node=call, args=("self.__class__",) ) continue try: supcls = call.args and next(call.args[0].infer(), None) except astroid.InferenceError: continue if klass is not supcls: name = None # if supcls is not Uninferable, then supcls was infered # and use its name. Otherwise, try to look # for call.args[0].name if supcls: name = supcls.name elif call.args and hasattr(call.args[0], "name"): name = call.args[0].name if name: self.add_message("bad-super-call", node=call, args=(name,))
[ "check", "use", "of", "super" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/newstyle.py#L58-L135
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "# 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", "if", "(", "len", "(", "call", ".", "args", ")", ">=", "2", "and", "isinstance", "(", "call", ".", "args", "[", "1", "]", ",", "astroid", ".", "Name", ")", "and", "call", ".", "args", "[", "1", "]", ".", "name", "==", "\"self\"", "and", "isinstance", "(", "arg0", ",", "astroid", ".", "Attribute", ")", "and", "arg0", ".", "attrname", "==", "\"__class__\"", ")", ":", "self", ".", "add_message", "(", "\"bad-super-call\"", ",", "node", "=", "call", ",", "args", "=", "(", "\"self.__class__\"", ",", ")", ")", "continue", "try", ":", "supcls", "=", "call", ".", "args", "and", "next", "(", "call", ".", "args", "[", "0", "]", ".", "infer", "(", ")", ",", "None", ")", "except", "astroid", ".", "InferenceError", ":", "continue", "if", "klass", "is", "not", "supcls", ":", "name", "=", "None", "# if supcls is not Uninferable, then supcls was infered", "# and use its name. Otherwise, try to look", "# for call.args[0].name", "if", "supcls", ":", "name", "=", "supcls", ".", "name", "elif", "call", ".", "args", "and", "hasattr", "(", "call", ".", "args", "[", "0", "]", ",", "\"name\"", ")", ":", "name", "=", "call", ".", "args", "[", "0", "]", ".", "name", "if", "name", ":", "self", ".", "add_message", "(", "\"bad-super-call\"", ",", "node", "=", "call", ",", "args", "=", "(", "name", ",", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BaseReporter.display_reports
display results encapsulated in the layout tree
pylint/reporters/base_reporter.py
def display_reports(self, layout): """display results encapsulated in the layout tree""" self.section = 0 if hasattr(layout, "report_id"): layout.children[0].children[0].data += " (%s)" % layout.report_id self._display(layout)
def display_reports(self, layout): """display results encapsulated in the layout tree""" self.section = 0 if hasattr(layout, "report_id"): layout.children[0].children[0].data += " (%s)" % layout.report_id self._display(layout)
[ "display", "results", "encapsulated", "in", "the", "layout", "tree" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/reporters/base_reporter.py#L40-L45
[ "def", "display_reports", "(", "self", ",", "layout", ")", ":", "self", ".", "section", "=", "0", "if", "hasattr", "(", "layout", ",", "\"report_id\"", ")", ":", "layout", ".", "children", "[", "0", "]", ".", "children", "[", "0", "]", ".", "data", "+=", "\" (%s)\"", "%", "layout", ".", "report_id", "self", ".", "_display", "(", "layout", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_typing_namedtuple
Check if a class node is a typing.NamedTuple class
pylint/checkers/design_analysis.py
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool: """Check if a class node is a typing.NamedTuple class""" for base in node.ancestors(): if base.qname() == TYPING_NAMEDTUPLE: return True return False
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool: """Check if a class node is a typing.NamedTuple class""" for base in node.ancestors(): if base.qname() == TYPING_NAMEDTUPLE: return True return False
[ "Check", "if", "a", "class", "node", "is", "a", "typing", ".", "NamedTuple", "class" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L96-L101
[ "def", "_is_typing_namedtuple", "(", "node", ":", "astroid", ".", "ClassDef", ")", "->", "bool", ":", "for", "base", "in", "node", ".", "ancestors", "(", ")", ":", "if", "base", ".", "qname", "(", ")", "==", "TYPING_NAMEDTUPLE", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_enum_class
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
pylint/checkers/design_analysis.py
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 inferred_bases: if not isinstance(ancestor, astroid.ClassDef): continue if ancestor.name == "Enum" and ancestor.root().name == "enum": return True return False
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 inferred_bases: if not isinstance(ancestor, astroid.ClassDef): continue if ancestor.name == "Enum" and ancestor.root().name == "enum": return True return False
[ "Check", "if", "a", "class", "definition", "defines", "an", "Enum", "class", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L104-L126
[ "def", "_is_enum_class", "(", "node", ":", "astroid", ".", "ClassDef", ")", "->", "bool", ":", "for", "base", "in", "node", ".", "bases", ":", "try", ":", "inferred_bases", "=", "base", ".", "inferred", "(", ")", "except", "astroid", ".", "InferenceError", ":", "continue", "for", "ancestor", "in", "inferred_bases", ":", "if", "not", "isinstance", "(", "ancestor", ",", "astroid", ".", "ClassDef", ")", ":", "continue", "if", "ancestor", ".", "name", "==", "\"Enum\"", "and", "ancestor", ".", "root", "(", ")", ".", "name", "==", "\"enum\"", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_dataclass
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
pylint/checkers/design_analysis.py
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 root_locals = node.root().locals for decorator in node.decorators.nodes: if isinstance(decorator, astroid.Call): decorator = decorator.func if not isinstance(decorator, (astroid.Name, astroid.Attribute)): continue if isinstance(decorator, astroid.Name): name = decorator.name else: name = decorator.attrname if name == DATACLASS_DECORATOR and DATACLASS_DECORATOR in root_locals: return True return False
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 root_locals = node.root().locals for decorator in node.decorators.nodes: if isinstance(decorator, astroid.Call): decorator = decorator.func if not isinstance(decorator, (astroid.Name, astroid.Attribute)): continue if isinstance(decorator, astroid.Name): name = decorator.name else: name = decorator.attrname if name == DATACLASS_DECORATOR and DATACLASS_DECORATOR in root_locals: return True return False
[ "Check", "if", "a", "class", "definition", "defines", "a", "Python", "3", ".", "7", "+", "dataclass" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L129-L153
[ "def", "_is_dataclass", "(", "node", ":", "astroid", ".", "ClassDef", ")", "->", "bool", ":", "if", "not", "node", ".", "decorators", ":", "return", "False", "root_locals", "=", "node", ".", "root", "(", ")", ".", "locals", "for", "decorator", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "isinstance", "(", "decorator", ",", "astroid", ".", "Call", ")", ":", "decorator", "=", "decorator", ".", "func", "if", "not", "isinstance", "(", "decorator", ",", "(", "astroid", ".", "Name", ",", "astroid", ".", "Attribute", ")", ")", ":", "continue", "if", "isinstance", "(", "decorator", ",", "astroid", ".", "Name", ")", ":", "name", "=", "decorator", ".", "name", "else", ":", "name", "=", "decorator", ".", "attrname", "if", "name", "==", "DATACLASS_DECORATOR", "and", "DATACLASS_DECORATOR", "in", "root_locals", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_count_boolean_expressions
Counts the number of boolean expressions in BoolOp `bool_op` (recursive) example: a and (b or c or (d and e)) ==> 5 boolean expressions
pylint/checkers/design_analysis.py
def _count_boolean_expressions(bool_op): """Counts the number of boolean expressions in BoolOp `bool_op` (recursive) example: a and (b or c or (d and e)) ==> 5 boolean expressions """ nb_bool_expr = 0 for bool_expr in bool_op.get_children(): if isinstance(bool_expr, BoolOp): nb_bool_expr += _count_boolean_expressions(bool_expr) else: nb_bool_expr += 1 return nb_bool_expr
def _count_boolean_expressions(bool_op): """Counts the number of boolean expressions in BoolOp `bool_op` (recursive) example: a and (b or c or (d and e)) ==> 5 boolean expressions """ nb_bool_expr = 0 for bool_expr in bool_op.get_children(): if isinstance(bool_expr, BoolOp): nb_bool_expr += _count_boolean_expressions(bool_expr) else: nb_bool_expr += 1 return nb_bool_expr
[ "Counts", "the", "number", "of", "boolean", "expressions", "in", "BoolOp", "bool_op", "(", "recursive", ")" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L156-L167
[ "def", "_count_boolean_expressions", "(", "bool_op", ")", ":", "nb_bool_expr", "=", "0", "for", "bool_expr", "in", "bool_op", ".", "get_children", "(", ")", ":", "if", "isinstance", "(", "bool_expr", ",", "BoolOp", ")", ":", "nb_bool_expr", "+=", "_count_boolean_expressions", "(", "bool_expr", ")", "else", ":", "nb_bool_expr", "+=", "1", "return", "nb_bool_expr" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.open
initialize visit variables
pylint/checkers/design_analysis.py
def open(self): """initialize visit variables""" self.stats = self.linter.add_stats() self._returns = [] self._branches = defaultdict(int) self._stmts = []
def open(self): """initialize visit variables""" self.stats = self.linter.add_stats() self._returns = [] self._branches = defaultdict(int) self._stmts = []
[ "initialize", "visit", "variables" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L299-L304
[ "def", "open", "(", "self", ")", ":", "self", ".", "stats", "=", "self", ".", "linter", ".", "add_stats", "(", ")", "self", ".", "_returns", "=", "[", "]", "self", ".", "_branches", "=", "defaultdict", "(", "int", ")", "self", ".", "_stmts", "=", "[", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.visit_classdef
check size of inheritance hierarchy and number of instance attributes
pylint/checkers/design_analysis.py
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( "too-many-ancestors", node=node, args=(nb_parents, self.config.max_parents), ) if len(node.instance_attrs) > self.config.max_attributes: self.add_message( "too-many-instance-attributes", node=node, args=(len(node.instance_attrs), self.config.max_attributes), )
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( "too-many-ancestors", node=node, args=(nb_parents, self.config.max_parents), ) if len(node.instance_attrs) > self.config.max_attributes: self.add_message( "too-many-instance-attributes", node=node, args=(len(node.instance_attrs), self.config.max_attributes), )
[ "check", "size", "of", "inheritance", "hierarchy", "and", "number", "of", "instance", "attributes" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L320-L336
[ "def", "visit_classdef", "(", "self", ",", "node", ")", ":", "nb_parents", "=", "len", "(", "list", "(", "node", ".", "ancestors", "(", ")", ")", ")", "if", "nb_parents", ">", "self", ".", "config", ".", "max_parents", ":", "self", ".", "add_message", "(", "\"too-many-ancestors\"", ",", "node", "=", "node", ",", "args", "=", "(", "nb_parents", ",", "self", ".", "config", ".", "max_parents", ")", ",", ")", "if", "len", "(", "node", ".", "instance_attrs", ")", ">", "self", ".", "config", ".", "max_attributes", ":", "self", ".", "add_message", "(", "\"too-many-instance-attributes\"", ",", "node", "=", "node", ",", "args", "=", "(", "len", "(", "node", ".", "instance_attrs", ")", ",", "self", ".", "config", ".", "max_attributes", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.leave_classdef
check number of public methods
pylint/checkers/design_analysis.py
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" or _is_enum_class(node) or _is_dataclass(node) or _is_typing_namedtuple(node) ): return # Does the class contain more than n public methods ? # This checks all the methods defined by ancestors and # by the current class. all_methods = _count_methods_in_class(node) if all_methods < self.config.min_public_methods: self.add_message( "too-few-public-methods", node=node, args=(all_methods, self.config.min_public_methods), )
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" or _is_enum_class(node) or _is_dataclass(node) or _is_typing_namedtuple(node) ): return # Does the class contain more than n public methods ? # This checks all the methods defined by ancestors and # by the current class. all_methods = _count_methods_in_class(node) if all_methods < self.config.min_public_methods: self.add_message( "too-few-public-methods", node=node, args=(all_methods, self.config.min_public_methods), )
[ "check", "number", "of", "public", "methods" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L339-L378
[ "def", "leave_classdef", "(", "self", ",", "node", ")", ":", "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\"", "or", "_is_enum_class", "(", "node", ")", "or", "_is_dataclass", "(", "node", ")", "or", "_is_typing_namedtuple", "(", "node", ")", ")", ":", "return", "# Does the class contain more than n public methods ?", "# This checks all the methods defined by ancestors and", "# by the current class.", "all_methods", "=", "_count_methods_in_class", "(", "node", ")", "if", "all_methods", "<", "self", ".", "config", ".", "min_public_methods", ":", "self", ".", "add_message", "(", "\"too-few-public-methods\"", ",", "node", "=", "node", ",", "args", "=", "(", "all_methods", ",", "self", ".", "config", ".", "min_public_methods", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.visit_functiondef
check function name, docstring, arguments, redefinition, variable names, max locals
pylint/checkers/design_analysis.py
def visit_functiondef(self, node): """check function name, docstring, arguments, redefinition, variable names, max locals """ # init branch and returns counters self._returns.append(0) # check number of arguments args = node.args.args ignored_argument_names = self._ignored_argument_names if args is not None: ignored_args_num = 0 if ignored_argument_names: ignored_args_num = sum( 1 for arg in args if ignored_argument_names.match(arg.name) ) argnum = len(args) - ignored_args_num if argnum > self.config.max_args: self.add_message( "too-many-arguments", node=node, args=(len(args), self.config.max_args), ) else: ignored_args_num = 0 # check number of local variables locnum = len(node.locals) - ignored_args_num if locnum > self.config.max_locals: self.add_message( "too-many-locals", node=node, args=(locnum, self.config.max_locals) ) # init new statements counter self._stmts.append(1)
def visit_functiondef(self, node): """check function name, docstring, arguments, redefinition, variable names, max locals """ # init branch and returns counters self._returns.append(0) # check number of arguments args = node.args.args ignored_argument_names = self._ignored_argument_names if args is not None: ignored_args_num = 0 if ignored_argument_names: ignored_args_num = sum( 1 for arg in args if ignored_argument_names.match(arg.name) ) argnum = len(args) - ignored_args_num if argnum > self.config.max_args: self.add_message( "too-many-arguments", node=node, args=(len(args), self.config.max_args), ) else: ignored_args_num = 0 # check number of local variables locnum = len(node.locals) - ignored_args_num if locnum > self.config.max_locals: self.add_message( "too-many-locals", node=node, args=(locnum, self.config.max_locals) ) # init new statements counter self._stmts.append(1)
[ "check", "function", "name", "docstring", "arguments", "redefinition", "variable", "names", "max", "locals" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L388-L420
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "# init branch and returns counters", "self", ".", "_returns", ".", "append", "(", "0", ")", "# check number of arguments", "args", "=", "node", ".", "args", ".", "args", "ignored_argument_names", "=", "self", ".", "_ignored_argument_names", "if", "args", "is", "not", "None", ":", "ignored_args_num", "=", "0", "if", "ignored_argument_names", ":", "ignored_args_num", "=", "sum", "(", "1", "for", "arg", "in", "args", "if", "ignored_argument_names", ".", "match", "(", "arg", ".", "name", ")", ")", "argnum", "=", "len", "(", "args", ")", "-", "ignored_args_num", "if", "argnum", ">", "self", ".", "config", ".", "max_args", ":", "self", ".", "add_message", "(", "\"too-many-arguments\"", ",", "node", "=", "node", ",", "args", "=", "(", "len", "(", "args", ")", ",", "self", ".", "config", ".", "max_args", ")", ",", ")", "else", ":", "ignored_args_num", "=", "0", "# check number of local variables", "locnum", "=", "len", "(", "node", ".", "locals", ")", "-", "ignored_args_num", "if", "locnum", ">", "self", ".", "config", ".", "max_locals", ":", "self", ".", "add_message", "(", "\"too-many-locals\"", ",", "node", "=", "node", ",", "args", "=", "(", "locnum", ",", "self", ".", "config", ".", "max_locals", ")", ")", "# init new statements counter", "self", ".", "_stmts", ".", "append", "(", "1", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.leave_functiondef
most of the work is done here on close: checks for max returns, branch, return in __init__
pylint/checkers/design_analysis.py
def leave_functiondef(self, node): """most of the work is done here on close: checks for max returns, branch, return in __init__ """ returns = self._returns.pop() if returns > self.config.max_returns: self.add_message( "too-many-return-statements", node=node, args=(returns, self.config.max_returns), ) branches = self._branches[node] if branches > self.config.max_branches: self.add_message( "too-many-branches", node=node, args=(branches, self.config.max_branches), ) # check number of statements stmts = self._stmts.pop() if stmts > self.config.max_statements: self.add_message( "too-many-statements", node=node, args=(stmts, self.config.max_statements), )
def leave_functiondef(self, node): """most of the work is done here on close: checks for max returns, branch, return in __init__ """ returns = self._returns.pop() if returns > self.config.max_returns: self.add_message( "too-many-return-statements", node=node, args=(returns, self.config.max_returns), ) branches = self._branches[node] if branches > self.config.max_branches: self.add_message( "too-many-branches", node=node, args=(branches, self.config.max_branches), ) # check number of statements stmts = self._stmts.pop() if stmts > self.config.max_statements: self.add_message( "too-many-statements", node=node, args=(stmts, self.config.max_statements), )
[ "most", "of", "the", "work", "is", "done", "here", "on", "close", ":", "checks", "for", "max", "returns", "branch", "return", "in", "__init__" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L431-L456
[ "def", "leave_functiondef", "(", "self", ",", "node", ")", ":", "returns", "=", "self", ".", "_returns", ".", "pop", "(", ")", "if", "returns", ">", "self", ".", "config", ".", "max_returns", ":", "self", ".", "add_message", "(", "\"too-many-return-statements\"", ",", "node", "=", "node", ",", "args", "=", "(", "returns", ",", "self", ".", "config", ".", "max_returns", ")", ",", ")", "branches", "=", "self", ".", "_branches", "[", "node", "]", "if", "branches", ">", "self", ".", "config", ".", "max_branches", ":", "self", ".", "add_message", "(", "\"too-many-branches\"", ",", "node", "=", "node", ",", "args", "=", "(", "branches", ",", "self", ".", "config", ".", "max_branches", ")", ",", ")", "# check number of statements", "stmts", "=", "self", ".", "_stmts", ".", "pop", "(", ")", "if", "stmts", ">", "self", ".", "config", ".", "max_statements", ":", "self", ".", "add_message", "(", "\"too-many-statements\"", ",", "node", "=", "node", ",", "args", "=", "(", "stmts", ",", "self", ".", "config", ".", "max_statements", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.visit_tryexcept
increments the branches counter
pylint/checkers/design_analysis.py
def visit_tryexcept(self, node): """increments the branches counter""" branches = len(node.handlers) if node.orelse: branches += 1 self._inc_branch(node, branches) self._inc_all_stmts(branches)
def visit_tryexcept(self, node): """increments the branches counter""" branches = len(node.handlers) if node.orelse: branches += 1 self._inc_branch(node, branches) self._inc_all_stmts(branches)
[ "increments", "the", "branches", "counter" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L473-L479
[ "def", "visit_tryexcept", "(", "self", ",", "node", ")", ":", "branches", "=", "len", "(", "node", ".", "handlers", ")", "if", "node", ".", "orelse", ":", "branches", "+=", "1", "self", ".", "_inc_branch", "(", "node", ",", "branches", ")", "self", ".", "_inc_all_stmts", "(", "branches", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.visit_if
increments the branches counter and checks boolean expressions
pylint/checkers/design_analysis.py
def visit_if(self, node): """increments the branches counter and checks boolean expressions""" self._check_boolean_expressions(node) branches = 1 # don't double count If nodes coming from some 'elif' if node.orelse and (len(node.orelse) > 1 or not isinstance(node.orelse[0], If)): branches += 1 self._inc_branch(node, branches) self._inc_all_stmts(branches)
def visit_if(self, node): """increments the branches counter and checks boolean expressions""" self._check_boolean_expressions(node) branches = 1 # don't double count If nodes coming from some 'elif' if node.orelse and (len(node.orelse) > 1 or not isinstance(node.orelse[0], If)): branches += 1 self._inc_branch(node, branches) self._inc_all_stmts(branches)
[ "increments", "the", "branches", "counter", "and", "checks", "boolean", "expressions" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L487-L495
[ "def", "visit_if", "(", "self", ",", "node", ")", ":", "self", ".", "_check_boolean_expressions", "(", "node", ")", "branches", "=", "1", "# don't double count If nodes coming from some 'elif'", "if", "node", ".", "orelse", "and", "(", "len", "(", "node", ".", "orelse", ")", ">", "1", "or", "not", "isinstance", "(", "node", ".", "orelse", "[", "0", "]", ",", "If", ")", ")", ":", "branches", "+=", "1", "self", ".", "_inc_branch", "(", "node", ",", "branches", ")", "self", ".", "_inc_all_stmts", "(", "branches", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker._check_boolean_expressions
Go through "if" node `node` and counts its boolean expressions if the "if" node test is a BoolOp node
pylint/checkers/design_analysis.py
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 > self.config.max_bool_expr: self.add_message( "too-many-boolean-expressions", node=condition, args=(nb_bool_expr, self.config.max_bool_expr), )
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 > self.config.max_bool_expr: self.add_message( "too-many-boolean-expressions", node=condition, args=(nb_bool_expr, self.config.max_bool_expr), )
[ "Go", "through", "if", "node", "node", "and", "counts", "its", "boolean", "expressions" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L497-L511
[ "def", "_check_boolean_expressions", "(", "self", ",", "node", ")", ":", "condition", "=", "node", ".", "test", "if", "not", "isinstance", "(", "condition", ",", "BoolOp", ")", ":", "return", "nb_bool_expr", "=", "_count_boolean_expressions", "(", "condition", ")", "if", "nb_bool_expr", ">", "self", ".", "config", ".", "max_bool_expr", ":", "self", ".", "add_message", "(", "\"too-many-boolean-expressions\"", ",", "node", "=", "condition", ",", "args", "=", "(", "nb_bool_expr", ",", "self", ".", "config", ".", "max_bool_expr", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MisdesignChecker.visit_while
increments the branches counter
pylint/checkers/design_analysis.py
def visit_while(self, node): """increments the branches counter""" branches = 1 if node.orelse: branches += 1 self._inc_branch(node, branches)
def visit_while(self, node): """increments the branches counter""" branches = 1 if node.orelse: branches += 1 self._inc_branch(node, branches)
[ "increments", "the", "branches", "counter" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/design_analysis.py#L513-L518
[ "def", "visit_while", "(", "self", ",", "node", ")", ":", "branches", "=", "1", "if", "node", ".", "orelse", ":", "branches", "+=", "1", "self", ".", "_inc_branch", "(", "node", ",", "branches", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
SpellingChecker._check_docstring
check the node has any spelling errors
pylint/checkers/spelling.py
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 for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
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 for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
[ "check", "the", "node", "has", "any", "spelling", "errors" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/spelling.py#L388-L398
[ "def", "_check_docstring", "(", "self", ",", "node", ")", ":", "docstring", "=", "node", ".", "doc", "if", "not", "docstring", ":", "return", "start_line", "=", "node", ".", "lineno", "+", "1", "# Go through lines of docstring", "for", "idx", ",", "line", "in", "enumerate", "(", "docstring", ".", "splitlines", "(", ")", ")", ":", "self", ".", "_check_spelling", "(", "\"wrong-spelling-in-docstring\"", ",", "line", ",", "start_line", "+", "idx", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Message.format
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
pylint/message/message.py
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 """ # For some reason, _asdict on derived namedtuples does not work with # Python 3.4. Needs some investigation. return template.format(**dict(zip(self._fields, self)))
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 """ # For some reason, _asdict on derived namedtuples does not work with # Python 3.4. Needs some investigation. return template.format(**dict(zip(self._fields, self)))
[ "Format", "the", "message", "according", "to", "the", "given", "template", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message.py#L45-L53
[ "def", "format", "(", "self", ",", "template", ")", ":", "# For some reason, _asdict on derived namedtuples does not work with", "# Python 3.4. Needs some investigation.", "return", "template", ".", "format", "(", "*", "*", "dict", "(", "zip", "(", "self", ".", "_fields", ",", "self", ")", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_len_call
Checks if node is len(SOMETHING).
pylint/checkers/refactoring.py
def _is_len_call(node): """Checks if node is len(SOMETHING).""" return ( isinstance(node, astroid.Call) and isinstance(node.func, astroid.Name) and node.func.name == "len" )
def _is_len_call(node): """Checks if node is len(SOMETHING).""" return ( isinstance(node, astroid.Call) and isinstance(node.func, astroid.Name) and node.func.name == "len" )
[ "Checks", "if", "node", "is", "len", "(", "SOMETHING", ")", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L47-L53
[ "def", "_is_len_call", "(", "node", ")", ":", "return", "(", "isinstance", "(", "node", ",", "astroid", ".", "Call", ")", "and", "isinstance", "(", "node", ".", "func", ",", "astroid", ".", "Name", ")", "and", "node", ".", "func", ".", "name", "==", "\"len\"", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_trailing_comma
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
pylint/checkers/refactoring.py
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], left_tokens, ) ) # Note: If the newline is tokenize.NEWLINE and not tokenize.NL # then the newline denotes the end of expression is_last_element = all( other_token.type in (tokenize.NEWLINE, tokenize.COMMENT) for other_token in same_line_remaining_tokens ) if not same_line_remaining_tokens or not is_last_element: return False def get_curline_index_start(): """Get the index denoting the start of the current line""" for subindex, token in enumerate(reversed(tokens[:index])): # See Lib/tokenize.py and Lib/token.py in cpython for more info if token.type in (tokenize.NEWLINE, tokenize.NL): return index - subindex return 0 curline_start = get_curline_index_start() expected_tokens = {"return", "yield"} for prevtoken in tokens[curline_start:index]: if "=" in prevtoken.string or prevtoken.string in expected_tokens: return True return False
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], left_tokens, ) ) # Note: If the newline is tokenize.NEWLINE and not tokenize.NL # then the newline denotes the end of expression is_last_element = all( other_token.type in (tokenize.NEWLINE, tokenize.COMMENT) for other_token in same_line_remaining_tokens ) if not same_line_remaining_tokens or not is_last_element: return False def get_curline_index_start(): """Get the index denoting the start of the current line""" for subindex, token in enumerate(reversed(tokens[:index])): # See Lib/tokenize.py and Lib/token.py in cpython for more info if token.type in (tokenize.NEWLINE, tokenize.NL): return index - subindex return 0 curline_start = get_curline_index_start() expected_tokens = {"return", "yield"} for prevtoken in tokens[curline_start:index]: if "=" in prevtoken.string or prevtoken.string in expected_tokens: return True return False
[ "Check", "if", "the", "given", "token", "is", "a", "trailing", "comma" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L65-L107
[ "def", "_is_trailing_comma", "(", "tokens", ",", "index", ")", ":", "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", "]", ",", "left_tokens", ",", ")", ")", "# Note: If the newline is tokenize.NEWLINE and not tokenize.NL", "# then the newline denotes the end of expression", "is_last_element", "=", "all", "(", "other_token", ".", "type", "in", "(", "tokenize", ".", "NEWLINE", ",", "tokenize", ".", "COMMENT", ")", "for", "other_token", "in", "same_line_remaining_tokens", ")", "if", "not", "same_line_remaining_tokens", "or", "not", "is_last_element", ":", "return", "False", "def", "get_curline_index_start", "(", ")", ":", "\"\"\"Get the index denoting the start of the current line\"\"\"", "for", "subindex", ",", "token", "in", "enumerate", "(", "reversed", "(", "tokens", "[", ":", "index", "]", ")", ")", ":", "# See Lib/tokenize.py and Lib/token.py in cpython for more info", "if", "token", ".", "type", "in", "(", "tokenize", ".", "NEWLINE", ",", "tokenize", ".", "NL", ")", ":", "return", "index", "-", "subindex", "return", "0", "curline_start", "=", "get_curline_index_start", "(", ")", "expected_tokens", "=", "{", "\"return\"", ",", "\"yield\"", "}", "for", "prevtoken", "in", "tokens", "[", "curline_start", ":", "index", "]", ":", "if", "\"=\"", "in", "prevtoken", ".", "string", "or", "prevtoken", ".", "string", "in", "expected_tokens", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
register
Required method to auto register this checker.
pylint/checkers/refactoring.py
def register(linter): """Required method to auto register this checker.""" linter.register_checker(RefactoringChecker(linter)) linter.register_checker(NotChecker(linter)) linter.register_checker(RecommandationChecker(linter)) linter.register_checker(LenChecker(linter))
def register(linter): """Required method to auto register this checker.""" linter.register_checker(RefactoringChecker(linter)) linter.register_checker(NotChecker(linter)) linter.register_checker(RecommandationChecker(linter)) linter.register_checker(LenChecker(linter))
[ "Required", "method", "to", "auto", "register", "this", "checker", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L1376-L1381
[ "def", "register", "(", "linter", ")", ":", "linter", ".", "register_checker", "(", "RefactoringChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "NotChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "RecommandationChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "LenChecker", "(", "linter", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._is_actual_elif
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 type in certain cases.
pylint/checkers/refactoring.py
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 type in certain cases. """ if isinstance(node.parent, astroid.If): orelse = node.parent.orelse # current if node must directly follow an "else" if orelse and orelse == [node]: if (node.lineno, node.col_offset) in self._elifs: return True return False
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 type in certain cases. """ if isinstance(node.parent, astroid.If): orelse = node.parent.orelse # current if node must directly follow an "else" if orelse and orelse == [node]: if (node.lineno, node.col_offset) in self._elifs: return True return False
[ "Check", "if", "the", "given", "node", "is", "an", "actual", "elif" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L319-L333
[ "def", "_is_actual_elif", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ".", "parent", ",", "astroid", ".", "If", ")", ":", "orelse", "=", "node", ".", "parent", ".", "orelse", "# current if node must directly follow an \"else\"", "if", "orelse", "and", "orelse", "==", "[", "node", "]", ":", "if", "(", "node", ".", "lineno", ",", "node", ".", "col_offset", ")", "in", "self", ".", "_elifs", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_simplifiable_if
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.
pylint/checkers/refactoring.py
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: return if not first_branch_is_bool or not else_branch_is_bool: return if not first_branch.value.value: # This is a case that can't be easily simplified and # if it can be simplified, it will usually result in a # code that's harder to understand and comprehend. # Let's take for instance `arg and arg <= 3`. This could theoretically be # reduced to `not arg or arg > 3`, but the net result is that now the # condition is harder to understand, because it requires understanding of # an extra clause: # * first, there is the negation of truthness with `not arg` # * the second clause is `arg > 3`, which occurs when arg has a # a truth value, but it implies that `arg > 3` is equivalent # with `arg and arg > 3`, which means that the user must # think about this assumption when evaluating `arg > 3`. # The original form is easier to grasp. return self.add_message("simplifiable-if-statement", node=node, args=(reduced_to,))
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: return if not first_branch_is_bool or not else_branch_is_bool: return if not first_branch.value.value: # This is a case that can't be easily simplified and # if it can be simplified, it will usually result in a # code that's harder to understand and comprehend. # Let's take for instance `arg and arg <= 3`. This could theoretically be # reduced to `not arg or arg > 3`, but the net result is that now the # condition is harder to understand, because it requires understanding of # an extra clause: # * first, there is the negation of truthness with `not arg` # * the second clause is `arg > 3`, which occurs when arg has a # a truth value, but it implies that `arg > 3` is equivalent # with `arg and arg > 3`, which means that the user must # think about this assumption when evaluating `arg > 3`. # The original form is easier to grasp. return self.add_message("simplifiable-if-statement", node=node, args=(reduced_to,))
[ "Check", "if", "the", "given", "if", "node", "can", "be", "simplified", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L335-L404
[ "def", "_check_simplifiable_if", "(", "self", ",", "node", ")", ":", "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", ":", "return", "if", "not", "first_branch_is_bool", "or", "not", "else_branch_is_bool", ":", "return", "if", "not", "first_branch", ".", "value", ".", "value", ":", "# This is a case that can't be easily simplified and", "# if it can be simplified, it will usually result in a", "# code that's harder to understand and comprehend.", "# Let's take for instance `arg and arg <= 3`. This could theoretically be", "# reduced to `not arg or arg > 3`, but the net result is that now the", "# condition is harder to understand, because it requires understanding of", "# an extra clause:", "# * first, there is the negation of truthness with `not arg`", "# * the second clause is `arg > 3`, which occurs when arg has a", "# a truth value, but it implies that `arg > 3` is equivalent", "# with `arg and arg > 3`, which means that the user must", "# think about this assumption when evaluating `arg > 3`.", "# The original form is easier to grasp.", "return", "self", ".", "add_message", "(", "\"simplifiable-if-statement\"", ",", "node", "=", "node", ",", "args", "=", "(", "reduced_to", ",", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_stop_iteration_inside_generator
Check if an exception of type StopIteration is raised inside a generator
pylint/checkers/refactoring.py
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) if exc is None or exc is astroid.Uninferable: return if self._check_exception_inherit_from_stopiteration(exc): self.add_message("stop-iteration-return", node=node)
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) if exc is None or exc is astroid.Uninferable: return if self._check_exception_inherit_from_stopiteration(exc): self.add_message("stop-iteration-return", node=node)
[ "Check", "if", "an", "exception", "of", "type", "StopIteration", "is", "raised", "inside", "a", "generator" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L595-L608
[ "def", "_check_stop_iteration_inside_generator", "(", "self", ",", "node", ")", ":", "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", ")", "if", "exc", "is", "None", "or", "exc", "is", "astroid", ".", "Uninferable", ":", "return", "if", "self", ".", "_check_exception_inherit_from_stopiteration", "(", "exc", ")", ":", "self", ".", "add_message", "(", "\"stop-iteration-return\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_exception_inherit_from_stopiteration
Return True if the exception node in argument inherit from StopIteration
pylint/checkers/refactoring.py
def _check_exception_inherit_from_stopiteration(exc): """Return True if the exception node in argument inherit from StopIteration""" stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE) return any(_class.qname() == stopiteration_qname for _class in exc.mro())
def _check_exception_inherit_from_stopiteration(exc): """Return True if the exception node in argument inherit from StopIteration""" stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE) return any(_class.qname() == stopiteration_qname for _class in exc.mro())
[ "Return", "True", "if", "the", "exception", "node", "in", "argument", "inherit", "from", "StopIteration" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L611-L614
[ "def", "_check_exception_inherit_from_stopiteration", "(", "exc", ")", ":", "stopiteration_qname", "=", "\"{}.StopIteration\"", ".", "format", "(", "utils", ".", "EXCEPTIONS_MODULE", ")", "return", "any", "(", "_class", ".", "qname", "(", ")", "==", "stopiteration_qname", "for", "_class", "in", "exc", ".", "mro", "(", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_raising_stopiteration_in_generator_next_call
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`
pylint/checkers/refactoring.py
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 has_sentinel_value = len(node.args) > 1 if ( isinstance(frame, astroid.FunctionDef) and frame.is_generator() and not has_sentinel_value and not utils.node_ignores_exception(node, StopIteration) and not _looks_like_infinite_iterator(node.args[0]) ): self.add_message("stop-iteration-return", node=node)
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 has_sentinel_value = len(node.args) > 1 if ( isinstance(frame, astroid.FunctionDef) and frame.is_generator() and not has_sentinel_value and not utils.node_ignores_exception(node, StopIteration) and not _looks_like_infinite_iterator(node.args[0]) ): self.add_message("stop-iteration-return", node=node)
[ "Check", "if", "a", "StopIteration", "exception", "is", "raised", "by", "the", "call", "to", "next", "function" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L635-L667
[ "def", "_check_raising_stopiteration_in_generator_next_call", "(", "self", ",", "node", ")", ":", "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", "has_sentinel_value", "=", "len", "(", "node", ".", "args", ")", ">", "1", "if", "(", "isinstance", "(", "frame", ",", "astroid", ".", "FunctionDef", ")", "and", "frame", ".", "is_generator", "(", ")", "and", "not", "has_sentinel_value", "and", "not", "utils", ".", "node_ignores_exception", "(", "node", ",", "StopIteration", ")", "and", "not", "_looks_like_infinite_iterator", "(", "node", ".", "args", "[", "0", "]", ")", ")", ":", "self", ".", "add_message", "(", "\"stop-iteration-return\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_nested_blocks
Update and check the number of nested blocks
pylint/checkers/refactoring.py
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 if isinstance(node, astroid.If) and self._is_actual_elif(node): if self._nested_blocks: self._nested_blocks.pop() self._nested_blocks.append(node) # send message only once per group of nested blocks if len(nested_blocks) > len(self._nested_blocks): self._emit_nested_blocks_message_if_needed(nested_blocks)
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 if isinstance(node, astroid.If) and self._is_actual_elif(node): if self._nested_blocks: self._nested_blocks.pop() self._nested_blocks.append(node) # send message only once per group of nested blocks if len(nested_blocks) > len(self._nested_blocks): self._emit_nested_blocks_message_if_needed(nested_blocks)
[ "Update", "and", "check", "the", "number", "of", "nested", "blocks" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L669-L694
[ "def", "_check_nested_blocks", "(", "self", ",", "node", ")", ":", "# 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", "if", "isinstance", "(", "node", ",", "astroid", ".", "If", ")", "and", "self", ".", "_is_actual_elif", "(", "node", ")", ":", "if", "self", ".", "_nested_blocks", ":", "self", ".", "_nested_blocks", ".", "pop", "(", ")", "self", ".", "_nested_blocks", ".", "append", "(", "node", ")", "# send message only once per group of nested blocks", "if", "len", "(", "nested_blocks", ")", ">", "len", "(", "self", ".", "_nested_blocks", ")", ":", "self", ".", "_emit_nested_blocks_message_if_needed", "(", "nested_blocks", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._duplicated_isinstance_types
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
pylint/checkers/refactoring.py
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) if isinstance(isinstance_types, astroid.Tuple): elems = [ class_type.as_string() for class_type in isinstance_types.itered() ] else: elems = [isinstance_types.as_string()] all_types[isinstance_object].update(elems) # Remove all keys which not duplicated return { key: value for key, value in all_types.items() if key in duplicated_objects }
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) if isinstance(isinstance_types, astroid.Tuple): elems = [ class_type.as_string() for class_type in isinstance_types.itered() ] else: elems = [isinstance_types.as_string()] all_types[isinstance_object].update(elems) # Remove all keys which not duplicated return { key: value for key, value in all_types.items() if key in duplicated_objects }
[ "Get", "the", "duplicated", "types", "from", "the", "underlying", "isinstance", "calls", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L705-L744
[ "def", "_duplicated_isinstance_types", "(", "node", ")", ":", "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", ")", "if", "isinstance", "(", "isinstance_types", ",", "astroid", ".", "Tuple", ")", ":", "elems", "=", "[", "class_type", ".", "as_string", "(", ")", "for", "class_type", "in", "isinstance_types", ".", "itered", "(", ")", "]", "else", ":", "elems", "=", "[", "isinstance_types", ".", "as_string", "(", ")", "]", "all_types", "[", "isinstance_object", "]", ".", "update", "(", "elems", ")", "# Remove all keys which not duplicated", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "all_types", ".", "items", "(", ")", "if", "key", "in", "duplicated_objects", "}" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_consider_merging_isinstance
Check isinstance calls which can be merged together.
pylint/checkers/refactoring.py
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) self.add_message( "consider-merging-isinstance", node=node, args=(duplicated_name, ", ".join(names)), )
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) self.add_message( "consider-merging-isinstance", node=node, args=(duplicated_name, ", ".join(names)), )
[ "Check", "isinstance", "calls", "which", "can", "be", "merged", "together", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L746-L758
[ "def", "_check_consider_merging_isinstance", "(", "self", ",", "node", ")", ":", "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", ")", "self", ".", "add_message", "(", "\"consider-merging-isinstance\"", ",", "node", "=", "node", ",", "args", "=", "(", "duplicated_name", ",", "\", \"", ".", "join", "(", "names", ")", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_chained_comparison
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.
pylint/checkers/refactoring.py
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: uses[value]["lower_bound"].add(comparison_node) left_operand = right_operand uses = collections.defaultdict( lambda: {"lower_bound": set(), "upper_bound": set()} ) for comparison_node in node.values: if isinstance(comparison_node, astroid.Compare): _find_lower_upper_bounds(comparison_node, uses) for _, bounds in uses.items(): num_shared = len(bounds["lower_bound"].intersection(bounds["upper_bound"])) num_lower_bounds = len(bounds["lower_bound"]) num_upper_bounds = len(bounds["upper_bound"]) if num_shared < num_lower_bounds and num_shared < num_upper_bounds: self.add_message("chained-comparison", node=node) break
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: uses[value]["lower_bound"].add(comparison_node) left_operand = right_operand uses = collections.defaultdict( lambda: {"lower_bound": set(), "upper_bound": set()} ) for comparison_node in node.values: if isinstance(comparison_node, astroid.Compare): _find_lower_upper_bounds(comparison_node, uses) for _, bounds in uses.items(): num_shared = len(bounds["lower_bound"].intersection(bounds["upper_bound"])) num_lower_bounds = len(bounds["lower_bound"]) num_upper_bounds = len(bounds["upper_bound"]) if num_shared < num_lower_bounds and num_shared < num_upper_bounds: self.add_message("chained-comparison", node=node) break
[ "Check", "if", "there", "is", "any", "chained", "comparison", "in", "the", "expression", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L803-L852
[ "def", "_check_chained_comparison", "(", "self", ",", "node", ")", ":", "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", ":", "uses", "[", "value", "]", "[", "\"lower_bound\"", "]", ".", "add", "(", "comparison_node", ")", "left_operand", "=", "right_operand", "uses", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "{", "\"lower_bound\"", ":", "set", "(", ")", ",", "\"upper_bound\"", ":", "set", "(", ")", "}", ")", "for", "comparison_node", "in", "node", ".", "values", ":", "if", "isinstance", "(", "comparison_node", ",", "astroid", ".", "Compare", ")", ":", "_find_lower_upper_bounds", "(", "comparison_node", ",", "uses", ")", "for", "_", ",", "bounds", "in", "uses", ".", "items", "(", ")", ":", "num_shared", "=", "len", "(", "bounds", "[", "\"lower_bound\"", "]", ".", "intersection", "(", "bounds", "[", "\"upper_bound\"", "]", ")", ")", "num_lower_bounds", "=", "len", "(", "bounds", "[", "\"lower_bound\"", "]", ")", "num_upper_bounds", "=", "len", "(", "bounds", "[", "\"upper_bound\"", "]", ")", "if", "num_shared", "<", "num_lower_bounds", "and", "num_shared", "<", "num_upper_bounds", ":", "self", ".", "add_message", "(", "\"chained-comparison\"", ",", "node", "=", "node", ")", "break" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_consider_using_join
We start with the augmented assignment and work our way upwards. Names of variables for nodes if match successful: result = '' # assign for number in ['1', '2', '3'] # for_loop result += number # aug_assign
pylint/checkers/refactoring.py
def _check_consider_using_join(self, aug_assign): """ We start with the augmented assignment and work our way upwards. Names of variables for nodes if match successful: result = '' # assign for number in ['1', '2', '3'] # for_loop result += number # aug_assign """ for_loop = aug_assign.parent if not isinstance(for_loop, astroid.For) or len(for_loop.body) > 1: return assign = for_loop.previous_sibling() if not isinstance(assign, astroid.Assign): return result_assign_names = { target.name for target in assign.targets if isinstance(target, astroid.AssignName) } is_concat_loop = ( aug_assign.op == "+=" and isinstance(aug_assign.target, astroid.AssignName) and len(for_loop.body) == 1 and aug_assign.target.name in result_assign_names and isinstance(assign.value, astroid.Const) and isinstance(assign.value.value, str) and isinstance(aug_assign.value, astroid.Name) and aug_assign.value.name == for_loop.target.name ) if is_concat_loop: self.add_message("consider-using-join", node=aug_assign)
def _check_consider_using_join(self, aug_assign): """ We start with the augmented assignment and work our way upwards. Names of variables for nodes if match successful: result = '' # assign for number in ['1', '2', '3'] # for_loop result += number # aug_assign """ for_loop = aug_assign.parent if not isinstance(for_loop, astroid.For) or len(for_loop.body) > 1: return assign = for_loop.previous_sibling() if not isinstance(assign, astroid.Assign): return result_assign_names = { target.name for target in assign.targets if isinstance(target, astroid.AssignName) } is_concat_loop = ( aug_assign.op == "+=" and isinstance(aug_assign.target, astroid.AssignName) and len(for_loop.body) == 1 and aug_assign.target.name in result_assign_names and isinstance(assign.value, astroid.Const) and isinstance(assign.value.value, str) and isinstance(aug_assign.value, astroid.Name) and aug_assign.value.name == for_loop.target.name ) if is_concat_loop: self.add_message("consider-using-join", node=aug_assign)
[ "We", "start", "with", "the", "augmented", "assignment", "and", "work", "our", "way", "upwards", ".", "Names", "of", "variables", "for", "nodes", "if", "match", "successful", ":", "result", "=", "#", "assign", "for", "number", "in", "[", "1", "2", "3", "]", "#", "for_loop", "result", "+", "=", "number", "#", "aug_assign" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L923-L954
[ "def", "_check_consider_using_join", "(", "self", ",", "aug_assign", ")", ":", "for_loop", "=", "aug_assign", ".", "parent", "if", "not", "isinstance", "(", "for_loop", ",", "astroid", ".", "For", ")", "or", "len", "(", "for_loop", ".", "body", ")", ">", "1", ":", "return", "assign", "=", "for_loop", ".", "previous_sibling", "(", ")", "if", "not", "isinstance", "(", "assign", ",", "astroid", ".", "Assign", ")", ":", "return", "result_assign_names", "=", "{", "target", ".", "name", "for", "target", "in", "assign", ".", "targets", "if", "isinstance", "(", "target", ",", "astroid", ".", "AssignName", ")", "}", "is_concat_loop", "=", "(", "aug_assign", ".", "op", "==", "\"+=\"", "and", "isinstance", "(", "aug_assign", ".", "target", ",", "astroid", ".", "AssignName", ")", "and", "len", "(", "for_loop", ".", "body", ")", "==", "1", "and", "aug_assign", ".", "target", ".", "name", "in", "result_assign_names", "and", "isinstance", "(", "assign", ".", "value", ",", "astroid", ".", "Const", ")", "and", "isinstance", "(", "assign", ".", "value", ".", "value", ",", "str", ")", "and", "isinstance", "(", "aug_assign", ".", "value", ",", "astroid", ".", "Name", ")", "and", "aug_assign", ".", "value", ".", "name", "==", "for_loop", ".", "target", ".", "name", ")", "if", "is_concat_loop", ":", "self", ".", "add_message", "(", "\"consider-using-join\"", ",", "node", "=", "aug_assign", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._is_and_or_ternary
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
pylint/checkers/refactoring.py
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 and isinstance(node.values[0], astroid.BoolOp) and not isinstance(node.values[1], astroid.BoolOp) and node.values[0].op == "and" and not isinstance(node.values[0].values[1], astroid.BoolOp) and len(node.values[0].values) == 2 )
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 and isinstance(node.values[0], astroid.BoolOp) and not isinstance(node.values[1], astroid.BoolOp) and node.values[0].op == "and" and not isinstance(node.values[0].values[1], astroid.BoolOp) and len(node.values[0].values) == 2 )
[ "Returns", "true", "if", "node", "is", "condition", "and", "true_value", "or", "false_value", "form", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L961-L976
[ "def", "_is_and_or_ternary", "(", "node", ")", ":", "return", "(", "isinstance", "(", "node", ",", "astroid", ".", "BoolOp", ")", "and", "node", ".", "op", "==", "\"or\"", "and", "len", "(", "node", ".", "values", ")", "==", "2", "and", "isinstance", "(", "node", ".", "values", "[", "0", "]", ",", "astroid", ".", "BoolOp", ")", "and", "not", "isinstance", "(", "node", ".", "values", "[", "1", "]", ",", "astroid", ".", "BoolOp", ")", "and", "node", ".", "values", "[", "0", "]", ".", "op", "==", "\"and\"", "and", "not", "isinstance", "(", "node", ".", "values", "[", "0", "]", ".", "values", "[", "1", "]", ",", "astroid", ".", "BoolOp", ")", "and", "len", "(", "node", ".", "values", "[", "0", "]", ".", "values", ")", "==", "2", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_consistent_returns
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.
pylint/checkers/refactoring.py
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 ] if not explicit_returns: return if len(explicit_returns) == len( self._return_nodes[node.name] ) and self._is_node_return_ended(node): return self.add_message("inconsistent-return-statements", node=node)
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 ] if not explicit_returns: return if len(explicit_returns) == len( self._return_nodes[node.name] ) and self._is_node_return_ended(node): return self.add_message("inconsistent-return-statements", node=node)
[ "Check", "that", "all", "return", "statements", "inside", "a", "function", "are", "consistent", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L989-L1010
[ "def", "_check_consistent_returns", "(", "self", ",", "node", ")", ":", "# 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", "]", "if", "not", "explicit_returns", ":", "return", "if", "len", "(", "explicit_returns", ")", "==", "len", "(", "self", ".", "_return_nodes", "[", "node", ".", "name", "]", ")", "and", "self", ".", "_is_node_return_ended", "(", "node", ")", ":", "return", "self", ".", "add_message", "(", "\"inconsistent-return-statements\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._is_node_return_ended
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.
pylint/checkers/refactoring.py
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 ) # if no handlers handle the exception then it's ok return True if isinstance(node, astroid.If): # if statement is returning if there are exactly two return statements in its #  children : one for the body part, the other for the orelse part # Do not check if inner function definition are return ended. is_orelse_returning = any( self._is_node_return_ended(_ore) for _ore in node.orelse if not isinstance(_ore, astroid.FunctionDef) ) is_if_returning = any( self._is_node_return_ended(_ifn) for _ifn in node.body if not isinstance(_ifn, astroid.FunctionDef) ) return is_if_returning and is_orelse_returning #  recurses on the children of the node except for those which are except handler # because one cannot be sure that the handler will really be used return any( self._is_node_return_ended(_child) for _child in node.get_children() if not isinstance(_child, astroid.ExceptHandler) )
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 ) # if no handlers handle the exception then it's ok return True if isinstance(node, astroid.If): # if statement is returning if there are exactly two return statements in its #  children : one for the body part, the other for the orelse part # Do not check if inner function definition are return ended. is_orelse_returning = any( self._is_node_return_ended(_ore) for _ore in node.orelse if not isinstance(_ore, astroid.FunctionDef) ) is_if_returning = any( self._is_node_return_ended(_ifn) for _ifn in node.body if not isinstance(_ifn, astroid.FunctionDef) ) return is_if_returning and is_orelse_returning #  recurses on the children of the node except for those which are except handler # because one cannot be sure that the handler will really be used return any( self._is_node_return_ended(_child) for _child in node.get_children() if not isinstance(_child, astroid.ExceptHandler) )
[ "Check", "if", "the", "node", "ends", "with", "an", "explicit", "return", "statement", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L1012-L1083
[ "def", "_is_node_return_ended", "(", "self", ",", "node", ")", ":", "#  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", ")", "# if no handlers handle the exception then it's ok", "return", "True", "if", "isinstance", "(", "node", ",", "astroid", ".", "If", ")", ":", "# if statement is returning if there are exactly two return statements in its", "#  children : one for the body part, the other for the orelse part", "# Do not check if inner function definition are return ended.", "is_orelse_returning", "=", "any", "(", "self", ".", "_is_node_return_ended", "(", "_ore", ")", "for", "_ore", "in", "node", ".", "orelse", "if", "not", "isinstance", "(", "_ore", ",", "astroid", ".", "FunctionDef", ")", ")", "is_if_returning", "=", "any", "(", "self", ".", "_is_node_return_ended", "(", "_ifn", ")", "for", "_ifn", "in", "node", ".", "body", "if", "not", "isinstance", "(", "_ifn", ",", "astroid", ".", "FunctionDef", ")", ")", "return", "is_if_returning", "and", "is_orelse_returning", "#  recurses on the children of the node except for those which are except handler", "# because one cannot be sure that the handler will really be used", "return", "any", "(", "self", ".", "_is_node_return_ended", "(", "_child", ")", "for", "_child", "in", "node", ".", "get_children", "(", ")", "if", "not", "isinstance", "(", "_child", ",", "astroid", ".", "ExceptHandler", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RefactoringChecker._check_return_at_the_end
Check for presence of a *single* return statement at the end of a function. "return" or "return None" are useless because None is the default return type if they are missing. NOTE: produces a message only if there is a single return statement in the function body. Otherwise _check_consistent_returns() is called! Per its implementation and PEP8 we can have a "return None" at the end of the function body if there are other return statements before that!
pylint/checkers/refactoring.py
def _check_return_at_the_end(self, node): """Check for presence of a *single* return statement at the end of a function. "return" or "return None" are useless because None is the default return type if they are missing. NOTE: produces a message only if there is a single return statement in the function body. Otherwise _check_consistent_returns() is called! Per its implementation and PEP8 we can have a "return None" at the end of the function body if there are other return statements before that! """ if len(self._return_nodes[node.name]) > 1: return if len(node.body) <= 1: return last = node.body[-1] if isinstance(last, astroid.Return): # e.g. "return" if last.value is None: self.add_message("useless-return", node=node) # return None" elif isinstance(last.value, astroid.Const) and (last.value.value is None): self.add_message("useless-return", node=node)
def _check_return_at_the_end(self, node): """Check for presence of a *single* return statement at the end of a function. "return" or "return None" are useless because None is the default return type if they are missing. NOTE: produces a message only if there is a single return statement in the function body. Otherwise _check_consistent_returns() is called! Per its implementation and PEP8 we can have a "return None" at the end of the function body if there are other return statements before that! """ if len(self._return_nodes[node.name]) > 1: return if len(node.body) <= 1: return last = node.body[-1] if isinstance(last, astroid.Return): # e.g. "return" if last.value is None: self.add_message("useless-return", node=node) # return None" elif isinstance(last.value, astroid.Const) and (last.value.value is None): self.add_message("useless-return", node=node)
[ "Check", "for", "presence", "of", "a", "*", "single", "*", "return", "statement", "at", "the", "end", "of", "a", "function", ".", "return", "or", "return", "None", "are", "useless", "because", "None", "is", "the", "default", "return", "type", "if", "they", "are", "missing", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L1099-L1121
[ "def", "_check_return_at_the_end", "(", "self", ",", "node", ")", ":", "if", "len", "(", "self", ".", "_return_nodes", "[", "node", ".", "name", "]", ")", ">", "1", ":", "return", "if", "len", "(", "node", ".", "body", ")", "<=", "1", ":", "return", "last", "=", "node", ".", "body", "[", "-", "1", "]", "if", "isinstance", "(", "last", ",", "astroid", ".", "Return", ")", ":", "# e.g. \"return\"", "if", "last", ".", "value", "is", "None", ":", "self", ".", "add_message", "(", "\"useless-return\"", ",", "node", "=", "node", ")", "# return None\"", "elif", "isinstance", "(", "last", ".", "value", ",", "astroid", ".", "Const", ")", "and", "(", "last", ".", "value", ".", "value", "is", "None", ")", ":", "self", ".", "add_message", "(", "\"useless-return\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RecommandationChecker.visit_for
Emit a convention whenever range and len are used for indexing.
pylint/checkers/refactoring.py
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 # for body. for child in node.body: for subscript in child.nodes_of_class(astroid.Subscript): if not isinstance(subscript.value, astroid.Name): continue if not isinstance(subscript.slice, astroid.Index): continue if not isinstance(subscript.slice.value, astroid.Name): continue if subscript.slice.value.name != node.target.name: continue if iterating_object.name != subscript.value.name: continue if subscript.value.scope() != node.scope(): # Ignore this subscript if it's not in the same # scope. This means that in the body of the for # loop, another scope was created, where the same # name for the iterating object was used. continue self.add_message("consider-using-enumerate", node=node) return
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 # for body. for child in node.body: for subscript in child.nodes_of_class(astroid.Subscript): if not isinstance(subscript.value, astroid.Name): continue if not isinstance(subscript.slice, astroid.Index): continue if not isinstance(subscript.slice.value, astroid.Name): continue if subscript.slice.value.name != node.target.name: continue if iterating_object.name != subscript.value.name: continue if subscript.value.scope() != node.scope(): # Ignore this subscript if it's not in the same # scope. This means that in the body of the for # loop, another scope was created, where the same # name for the iterating object was used. continue self.add_message("consider-using-enumerate", node=node) return
[ "Emit", "a", "convention", "whenever", "range", "and", "len", "are", "used", "for", "indexing", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L1165-L1221
[ "def", "visit_for", "(", "self", ",", "node", ")", ":", "# 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", "# for body.", "for", "child", "in", "node", ".", "body", ":", "for", "subscript", "in", "child", ".", "nodes_of_class", "(", "astroid", ".", "Subscript", ")", ":", "if", "not", "isinstance", "(", "subscript", ".", "value", ",", "astroid", ".", "Name", ")", ":", "continue", "if", "not", "isinstance", "(", "subscript", ".", "slice", ",", "astroid", ".", "Index", ")", ":", "continue", "if", "not", "isinstance", "(", "subscript", ".", "slice", ".", "value", ",", "astroid", ".", "Name", ")", ":", "continue", "if", "subscript", ".", "slice", ".", "value", ".", "name", "!=", "node", ".", "target", ".", "name", ":", "continue", "if", "iterating_object", ".", "name", "!=", "subscript", ".", "value", ".", "name", ":", "continue", "if", "subscript", ".", "value", ".", "scope", "(", ")", "!=", "node", ".", "scope", "(", ")", ":", "# Ignore this subscript if it's not in the same", "# scope. This means that in the body of the for", "# loop, another scope was created, where the same", "# name for the iterating object was used.", "continue", "self", ".", "add_message", "(", "\"consider-using-enumerate\"", ",", "node", "=", "node", ")", "return" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LenChecker.visit_unaryop
`not len(S)` must become `not S` regardless if the parent block is a test condition or something else (boolean expression) e.g. `if not len(S):`
pylint/checkers/refactoring.py
def visit_unaryop(self, node): """`not len(S)` must become `not S` regardless if the parent block is a test condition or something else (boolean expression) e.g. `if not len(S):`""" if ( isinstance(node, astroid.UnaryOp) and node.op == "not" and _is_len_call(node.operand) ): self.add_message("len-as-condition", node=node)
def visit_unaryop(self, node): """`not len(S)` must become `not S` regardless if the parent block is a test condition or something else (boolean expression) e.g. `if not len(S):`""" if ( isinstance(node, astroid.UnaryOp) and node.op == "not" and _is_len_call(node.operand) ): self.add_message("len-as-condition", node=node)
[ "not", "len", "(", "S", ")", "must", "become", "not", "S", "regardless", "if", "the", "parent", "block", "is", "a", "test", "condition", "or", "something", "else", "(", "boolean", "expression", ")", "e", ".", "g", ".", "if", "not", "len", "(", "S", ")", ":" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L1364-L1373
[ "def", "visit_unaryop", "(", "self", ",", "node", ")", ":", "if", "(", "isinstance", "(", "node", ",", "astroid", ".", "UnaryOp", ")", "and", "node", ".", "op", "==", "\"not\"", "and", "_is_len_call", "(", "node", ".", "operand", ")", ")", ":", "self", ".", "add_message", "(", "\"len-as-condition\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_check_graphviz_available
check if we need graphviz for different output format
pylint/pyreverse/main.py
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" "Please install 'Graphviz' to have other output formats " "than 'dot' or 'vcg'." % output_format ) sys.exit(32)
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" "Please install 'Graphviz' to have other output formats " "than 'dot' or 'vcg'." % output_format ) sys.exit(32)
[ "check", "if", "we", "need", "graphviz", "for", "different", "output", "format" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/main.py#L166-L176
[ "def", "_check_graphviz_available", "(", "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\"", "\"Please install 'Graphviz' to have other output formats \"", "\"than 'dot' or 'vcg'.\"", "%", "output_format", ")", "sys", ".", "exit", "(", "32", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Run.run
checking arguments and run project
pylint/pyreverse/main.py
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, ) linker = Linker(project, tag=True) handler = DiadefsHandler(self.config) diadefs = handler.get_diadefs(project, linker) finally: sys.path.pop(0) if self.config.output_format == "vcg": writer.VCGWriter(self.config).write(diadefs) else: writer.DotWriter(self.config).write(diadefs) return 0
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, ) linker = Linker(project, tag=True) handler = DiadefsHandler(self.config) diadefs = handler.get_diadefs(project, linker) finally: sys.path.pop(0) if self.config.output_format == "vcg": writer.VCGWriter(self.config).write(diadefs) else: writer.DotWriter(self.config).write(diadefs) return 0
[ "checking", "arguments", "and", "run", "project" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/main.py#L193-L217
[ "def", "run", "(", "self", ",", "args", ")", ":", "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", ",", ")", "linker", "=", "Linker", "(", "project", ",", "tag", "=", "True", ")", "handler", "=", "DiadefsHandler", "(", "self", ".", "config", ")", "diadefs", "=", "handler", ".", "get_diadefs", "(", "project", ",", "linker", ")", "finally", ":", "sys", ".", "path", ".", "pop", "(", "0", ")", "if", "self", ".", "config", ".", "output_format", "==", "\"vcg\"", ":", "writer", ".", "VCGWriter", "(", "self", ".", "config", ")", ".", "write", "(", "diadefs", ")", "else", ":", "writer", ".", "DotWriter", "(", "self", ".", "config", ")", ".", "write", "(", "diadefs", ")", "return", "0" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OverlappingExceptionsChecker.visit_tryexcept
check for empty except
pylint/extensions/overlapping_exceptions.py
def visit_tryexcept(self, node): """check for empty except""" for handler in node.handlers: if handler.type is None: continue if isinstance(handler.type, astroid.BoolOp): continue try: excs = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue handled_in_clause = [] for part, exc in excs: if exc is astroid.Uninferable: continue if isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex(exc): # pylint: disable=protected-access exc = exc._proxied if not isinstance(exc, astroid.ClassDef): continue exc_ancestors = [ anc for anc in exc.ancestors() if isinstance(anc, astroid.ClassDef) ] for prev_part, prev_exc in handled_in_clause: prev_exc_ancestors = [ anc for anc in prev_exc.ancestors() if isinstance(anc, astroid.ClassDef) ] if exc == prev_exc: self.add_message( "overlapping-except", node=handler.type, args="%s and %s are the same" % (prev_part.as_string(), part.as_string()), ) elif prev_exc in exc_ancestors or exc in prev_exc_ancestors: ancestor = part if exc in prev_exc_ancestors else prev_part descendant = part if prev_exc in exc_ancestors else prev_part self.add_message( "overlapping-except", node=handler.type, args="%s is an ancestor class of %s" % (ancestor.as_string(), descendant.as_string()), ) handled_in_clause += [(part, exc)]
def visit_tryexcept(self, node): """check for empty except""" for handler in node.handlers: if handler.type is None: continue if isinstance(handler.type, astroid.BoolOp): continue try: excs = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue handled_in_clause = [] for part, exc in excs: if exc is astroid.Uninferable: continue if isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex(exc): # pylint: disable=protected-access exc = exc._proxied if not isinstance(exc, astroid.ClassDef): continue exc_ancestors = [ anc for anc in exc.ancestors() if isinstance(anc, astroid.ClassDef) ] for prev_part, prev_exc in handled_in_clause: prev_exc_ancestors = [ anc for anc in prev_exc.ancestors() if isinstance(anc, astroid.ClassDef) ] if exc == prev_exc: self.add_message( "overlapping-except", node=handler.type, args="%s and %s are the same" % (prev_part.as_string(), part.as_string()), ) elif prev_exc in exc_ancestors or exc in prev_exc_ancestors: ancestor = part if exc in prev_exc_ancestors else prev_part descendant = part if prev_exc in exc_ancestors else prev_part self.add_message( "overlapping-except", node=handler.type, args="%s is an ancestor class of %s" % (ancestor.as_string(), descendant.as_string()), ) handled_in_clause += [(part, exc)]
[ "check", "for", "empty", "except" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/overlapping_exceptions.py#L34-L83
[ "def", "visit_tryexcept", "(", "self", ",", "node", ")", ":", "for", "handler", "in", "node", ".", "handlers", ":", "if", "handler", ".", "type", "is", "None", ":", "continue", "if", "isinstance", "(", "handler", ".", "type", ",", "astroid", ".", "BoolOp", ")", ":", "continue", "try", ":", "excs", "=", "list", "(", "_annotated_unpack_infer", "(", "handler", ".", "type", ")", ")", "except", "astroid", ".", "InferenceError", ":", "continue", "handled_in_clause", "=", "[", "]", "for", "part", ",", "exc", "in", "excs", ":", "if", "exc", "is", "astroid", ".", "Uninferable", ":", "continue", "if", "isinstance", "(", "exc", ",", "astroid", ".", "Instance", ")", "and", "utils", ".", "inherit_from_std_ex", "(", "exc", ")", ":", "# pylint: disable=protected-access", "exc", "=", "exc", ".", "_proxied", "if", "not", "isinstance", "(", "exc", ",", "astroid", ".", "ClassDef", ")", ":", "continue", "exc_ancestors", "=", "[", "anc", "for", "anc", "in", "exc", ".", "ancestors", "(", ")", "if", "isinstance", "(", "anc", ",", "astroid", ".", "ClassDef", ")", "]", "for", "prev_part", ",", "prev_exc", "in", "handled_in_clause", ":", "prev_exc_ancestors", "=", "[", "anc", "for", "anc", "in", "prev_exc", ".", "ancestors", "(", ")", "if", "isinstance", "(", "anc", ",", "astroid", ".", "ClassDef", ")", "]", "if", "exc", "==", "prev_exc", ":", "self", ".", "add_message", "(", "\"overlapping-except\"", ",", "node", "=", "handler", ".", "type", ",", "args", "=", "\"%s and %s are the same\"", "%", "(", "prev_part", ".", "as_string", "(", ")", ",", "part", ".", "as_string", "(", ")", ")", ",", ")", "elif", "prev_exc", "in", "exc_ancestors", "or", "exc", "in", "prev_exc_ancestors", ":", "ancestor", "=", "part", "if", "exc", "in", "prev_exc_ancestors", "else", "prev_part", "descendant", "=", "part", "if", "prev_exc", "in", "exc_ancestors", "else", "prev_part", "self", ".", "add_message", "(", "\"overlapping-except\"", ",", "node", "=", "handler", ".", "type", ",", "args", "=", "\"%s is an ancestor class of %s\"", "%", "(", "ancestor", ".", "as_string", "(", ")", ",", "descendant", ".", "as_string", "(", ")", ")", ",", ")", "handled_in_clause", "+=", "[", "(", "part", ",", "exc", ")", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DiagramWriter.write
write files for <project> according to <diadefs>
pylint/pyreverse/writer.py
def write(self, diadefs): """write files for <project> according to <diadefs> """ for diagram in diadefs: basename = diagram.title.strip().replace(" ", "_") file_name = "%s.%s" % (basename, self.config.output_format) self.set_printer(file_name, basename) if diagram.TYPE == "class": self.write_classes(diagram) else: self.write_packages(diagram) self.close_graph()
def write(self, diadefs): """write files for <project> according to <diadefs> """ for diagram in diadefs: basename = diagram.title.strip().replace(" ", "_") file_name = "%s.%s" % (basename, self.config.output_format) self.set_printer(file_name, basename) if diagram.TYPE == "class": self.write_classes(diagram) else: self.write_packages(diagram) self.close_graph()
[ "write", "files", "for", "<project", ">", "according", "to", "<diadefs", ">" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L30-L41
[ "def", "write", "(", "self", ",", "diadefs", ")", ":", "for", "diagram", "in", "diadefs", ":", "basename", "=", "diagram", ".", "title", ".", "strip", "(", ")", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "file_name", "=", "\"%s.%s\"", "%", "(", "basename", ",", "self", ".", "config", ".", "output_format", ")", "self", ".", "set_printer", "(", "file_name", ",", "basename", ")", "if", "diagram", ".", "TYPE", "==", "\"class\"", ":", "self", ".", "write_classes", "(", "diagram", ")", "else", ":", "self", ".", "write_packages", "(", "diagram", ")", "self", ".", "close_graph", "(", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DiagramWriter.write_packages
write a package diagram
pylint/pyreverse/writer.py
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 # package dependencies for rel in diagram.get_relationships("depends"): self.printer.emit_edge( rel.from_object.fig_id, rel.to_object.fig_id, **self.pkg_edges )
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 # package dependencies for rel in diagram.get_relationships("depends"): self.printer.emit_edge( rel.from_object.fig_id, rel.to_object.fig_id, **self.pkg_edges )
[ "write", "a", "package", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L43-L53
[ "def", "write_packages", "(", "self", ",", "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", "# package dependencies", "for", "rel", "in", "diagram", ".", "get_relationships", "(", "\"depends\"", ")", ":", "self", ".", "printer", ".", "emit_edge", "(", "rel", ".", "from_object", ".", "fig_id", ",", "rel", ".", "to_object", ".", "fig_id", ",", "*", "*", "self", ".", "pkg_edges", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DiagramWriter.write_classes
write a class diagram
pylint/pyreverse/writer.py
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( rel.from_object.fig_id, rel.to_object.fig_id, **self.imp_edges ) # generate associations for rel in diagram.get_relationships("association"): self.printer.emit_edge( rel.from_object.fig_id, rel.to_object.fig_id, label=rel.name, **self.association_edges )
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( rel.from_object.fig_id, rel.to_object.fig_id, **self.imp_edges ) # generate associations for rel in diagram.get_relationships("association"): self.printer.emit_edge( rel.from_object.fig_id, rel.to_object.fig_id, label=rel.name, **self.association_edges )
[ "write", "a", "class", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L55-L78
[ "def", "write_classes", "(", "self", ",", "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", "(", "rel", ".", "from_object", ".", "fig_id", ",", "rel", ".", "to_object", ".", "fig_id", ",", "*", "*", "self", ".", "imp_edges", ")", "# generate associations", "for", "rel", "in", "diagram", ".", "get_relationships", "(", "\"association\"", ")", ":", "self", ".", "printer", ".", "emit_edge", "(", "rel", ".", "from_object", ".", "fig_id", ",", "rel", ".", "to_object", ".", "fig_id", ",", "label", "=", "rel", ".", "name", ",", "*", "*", "self", ".", "association_edges", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotWriter.set_printer
initialize DotWriter and add options for layout.
pylint/pyreverse/writer.py
def set_printer(self, file_name, basename): """initialize DotWriter and add options for layout. """ layout = dict(rankdir="BT") self.printer = DotBackend(basename, additional_param=layout) self.file_name = file_name
def set_printer(self, file_name, basename): """initialize DotWriter and add options for layout. """ layout = dict(rankdir="BT") self.printer = DotBackend(basename, additional_param=layout) self.file_name = file_name
[ "initialize", "DotWriter", "and", "add", "options", "for", "layout", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L112-L117
[ "def", "set_printer", "(", "self", ",", "file_name", ",", "basename", ")", ":", "layout", "=", "dict", "(", "rankdir", "=", "\"BT\"", ")", "self", ".", "printer", "=", "DotBackend", "(", "basename", ",", "additional_param", "=", "layout", ")", "self", ".", "file_name", "=", "file_name" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotWriter.get_values
get label and shape for classes. The label contains all attributes and methods
pylint/pyreverse/writer.py
def get_values(self, obj): """get label and shape for classes. The label contains all attributes and methods """ label = obj.title if obj.shape == "interface": label = "«interface»\\n%s" % label if not self.config.only_classnames: label = r"%s|%s\l|" % (label, r"\l".join(obj.attrs)) for func in obj.methods: args = [arg.name for arg in func.args.args if arg.name != "self"] label = r"%s%s(%s)\l" % (label, func.name, ", ".join(args)) label = "{%s}" % label if is_exception(obj.node): return dict(fontcolor="red", label=label, shape="record") return dict(label=label, shape="record")
def get_values(self, obj): """get label and shape for classes. The label contains all attributes and methods """ label = obj.title if obj.shape == "interface": label = "«interface»\\n%s" % label if not self.config.only_classnames: label = r"%s|%s\l|" % (label, r"\l".join(obj.attrs)) for func in obj.methods: args = [arg.name for arg in func.args.args if arg.name != "self"] label = r"%s%s(%s)\l" % (label, func.name, ", ".join(args)) label = "{%s}" % label if is_exception(obj.node): return dict(fontcolor="red", label=label, shape="record") return dict(label=label, shape="record")
[ "get", "label", "and", "shape", "for", "classes", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L123-L139
[ "def", "get_values", "(", "self", ",", "obj", ")", ":", "label", "=", "obj", ".", "title", "if", "obj", ".", "shape", "==", "\"interface\"", ":", "label", "=", "\"«interface»\\\\n%s\" %", "l", "bel", "if", "not", "self", ".", "config", ".", "only_classnames", ":", "label", "=", "r\"%s|%s\\l|\"", "%", "(", "label", ",", "r\"\\l\"", ".", "join", "(", "obj", ".", "attrs", ")", ")", "for", "func", "in", "obj", ".", "methods", ":", "args", "=", "[", "arg", ".", "name", "for", "arg", "in", "func", ".", "args", ".", "args", "if", "arg", ".", "name", "!=", "\"self\"", "]", "label", "=", "r\"%s%s(%s)\\l\"", "%", "(", "label", ",", "func", ".", "name", ",", "\", \"", ".", "join", "(", "args", ")", ")", "label", "=", "\"{%s}\"", "%", "label", "if", "is_exception", "(", "obj", ".", "node", ")", ":", "return", "dict", "(", "fontcolor", "=", "\"red\"", ",", "label", "=", "label", ",", "shape", "=", "\"record\"", ")", "return", "dict", "(", "label", "=", "label", ",", "shape", "=", "\"record\"", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
VCGWriter.set_printer
initialize VCGWriter for a UML graph
pylint/pyreverse/writer.py
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", late_edge_labels="yes", port_sharing="no", manhattan_edges="yes", ) self.printer.emit_node = self.printer.node self.printer.emit_edge = self.printer.edge
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", late_edge_labels="yes", port_sharing="no", manhattan_edges="yes", ) self.printer.emit_node = self.printer.node self.printer.emit_edge = self.printer.edge
[ "initialize", "VCGWriter", "for", "a", "UML", "graph" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L164-L176
[ "def", "set_printer", "(", "self", ",", "file_name", ",", "basename", ")", ":", "self", ".", "graph_file", "=", "open", "(", "file_name", ",", "\"w+\"", ")", "self", ".", "printer", "=", "VCGPrinter", "(", "self", ".", "graph_file", ")", "self", ".", "printer", ".", "open_graph", "(", "title", "=", "basename", ",", "layoutalgorithm", "=", "\"dfs\"", ",", "late_edge_labels", "=", "\"yes\"", ",", "port_sharing", "=", "\"no\"", ",", "manhattan_edges", "=", "\"yes\"", ",", ")", "self", ".", "printer", ".", "emit_node", "=", "self", ".", "printer", ".", "node", "self", ".", "printer", ".", "emit_edge", "=", "self", ".", "printer", ".", "edge" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
VCGWriter.get_values
get label and shape for classes. The label contains all attributes and methods
pylint/pyreverse/writer.py
def get_values(self, obj): """get label and shape for classes. The label contains all attributes and methods """ if is_exception(obj.node): label = r"\fb\f09%s\fn" % obj.title else: label = r"\fb%s\fn" % obj.title if obj.shape == "interface": shape = "ellipse" else: shape = "box" if not self.config.only_classnames: attrs = obj.attrs methods = [func.name for func in obj.methods] # box width for UML like diagram maxlen = max(len(name) for name in [obj.title] + methods + attrs) line = "_" * (maxlen + 2) label = r"%s\n\f%s" % (label, line) for attr in attrs: label = r"%s\n\f08%s" % (label, attr) if attrs: label = r"%s\n\f%s" % (label, line) for func in methods: label = r"%s\n\f10%s()" % (label, func) return dict(label=label, shape=shape)
def get_values(self, obj): """get label and shape for classes. The label contains all attributes and methods """ if is_exception(obj.node): label = r"\fb\f09%s\fn" % obj.title else: label = r"\fb%s\fn" % obj.title if obj.shape == "interface": shape = "ellipse" else: shape = "box" if not self.config.only_classnames: attrs = obj.attrs methods = [func.name for func in obj.methods] # box width for UML like diagram maxlen = max(len(name) for name in [obj.title] + methods + attrs) line = "_" * (maxlen + 2) label = r"%s\n\f%s" % (label, line) for attr in attrs: label = r"%s\n\f08%s" % (label, attr) if attrs: label = r"%s\n\f%s" % (label, line) for func in methods: label = r"%s\n\f10%s()" % (label, func) return dict(label=label, shape=shape)
[ "get", "label", "and", "shape", "for", "classes", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/writer.py#L182-L208
[ "def", "get_values", "(", "self", ",", "obj", ")", ":", "if", "is_exception", "(", "obj", ".", "node", ")", ":", "label", "=", "r\"\\fb\\f09%s\\fn\"", "%", "obj", ".", "title", "else", ":", "label", "=", "r\"\\fb%s\\fn\"", "%", "obj", ".", "title", "if", "obj", ".", "shape", "==", "\"interface\"", ":", "shape", "=", "\"ellipse\"", "else", ":", "shape", "=", "\"box\"", "if", "not", "self", ".", "config", ".", "only_classnames", ":", "attrs", "=", "obj", ".", "attrs", "methods", "=", "[", "func", ".", "name", "for", "func", "in", "obj", ".", "methods", "]", "# box width for UML like diagram", "maxlen", "=", "max", "(", "len", "(", "name", ")", "for", "name", "in", "[", "obj", ".", "title", "]", "+", "methods", "+", "attrs", ")", "line", "=", "\"_\"", "*", "(", "maxlen", "+", "2", ")", "label", "=", "r\"%s\\n\\f%s\"", "%", "(", "label", ",", "line", ")", "for", "attr", "in", "attrs", ":", "label", "=", "r\"%s\\n\\f08%s\"", "%", "(", "label", ",", "attr", ")", "if", "attrs", ":", "label", "=", "r\"%s\\n\\f%s\"", "%", "(", "label", ",", "line", ")", "for", "func", "in", "methods", ":", "label", "=", "r\"%s\\n\\f10%s()\"", "%", "(", "label", ",", "func", ")", "return", "dict", "(", "label", "=", "label", ",", "shape", "=", "shape", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessageDefinition.may_be_emitted
return True if message may be emitted using the current interpreter
pylint/message/message_definition.py
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: return False if self.maxversion is not None and self.maxversion <= sys.version_info: return False return True
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: return False if self.maxversion is not None and self.maxversion <= sys.version_info: return False return True
[ "return", "True", "if", "message", "may", "be", "emitted", "using", "the", "current", "interpreter" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_definition.py#L43-L49
[ "def", "may_be_emitted", "(", "self", ")", ":", "if", "self", ".", "minversion", "is", "not", "None", "and", "self", ".", "minversion", ">", "sys", ".", "version_info", ":", "return", "False", "if", "self", ".", "maxversion", "is", "not", "None", "and", "self", ".", "maxversion", "<=", "sys", ".", "version_info", ":", "return", "False", "return", "True" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessageDefinition.format_help
return the help string for the given message id
pylint/message/message_definition.py
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])) restr = " or ".join(restr) if checkerref: desc += " It can't be emitted when using Python %s." % restr else: desc += " This message can't be emitted when using Python %s." % restr desc = normalize_text(" ".join(desc.split()), indent=" ") if title != "%s": title = title.splitlines()[0] return ":%s: *%s*\n%s" % (msgid, title.rstrip(" "), desc) return ":%s:\n%s" % (msgid, desc)
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])) restr = " or ".join(restr) if checkerref: desc += " It can't be emitted when using Python %s." % restr else: desc += " This message can't be emitted when using Python %s." % restr desc = normalize_text(" ".join(desc.split()), indent=" ") if title != "%s": title = title.splitlines()[0] return ":%s: *%s*\n%s" % (msgid, title.rstrip(" "), desc) return ":%s:\n%s" % (msgid, desc)
[ "return", "the", "help", "string", "for", "the", "given", "message", "id" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_definition.py#L51-L77
[ "def", "format_help", "(", "self", ",", "checkerref", "=", "False", ")", ":", "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", "]", ")", ")", "restr", "=", "\" or \"", ".", "join", "(", "restr", ")", "if", "checkerref", ":", "desc", "+=", "\" It can't be emitted when using Python %s.\"", "%", "restr", "else", ":", "desc", "+=", "\" This message can't be emitted when using Python %s.\"", "%", "restr", "desc", "=", "normalize_text", "(", "\" \"", ".", "join", "(", "desc", ".", "split", "(", ")", ")", ",", "indent", "=", "\" \"", ")", "if", "title", "!=", "\"%s\"", ":", "title", "=", "title", ".", "splitlines", "(", ")", "[", "0", "]", "return", "\":%s: *%s*\\n%s\"", "%", "(", "msgid", ",", "title", ".", "rstrip", "(", "\" \"", ")", ",", "desc", ")", "return", "\":%s:\\n%s\"", "%", "(", "msgid", ",", "desc", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MyRawChecker.process_module
process a module the module's content is accessible via node.stream() function
examples/custom_raw.py
def process_module(self, node): """process a module the module's content is accessible via node.stream() function """ with node.stream() as stream: for (lineno, line) in enumerate(stream): if line.rstrip().endswith("\\"): self.add_message("backslash-line-continuation", line=lineno)
def process_module(self, node): """process a module the module's content is accessible via node.stream() function """ with node.stream() as stream: for (lineno, line) in enumerate(stream): if line.rstrip().endswith("\\"): self.add_message("backslash-line-continuation", line=lineno)
[ "process", "a", "module" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/examples/custom_raw.py#L25-L33
[ "def", "process_module", "(", "self", ",", "node", ")", ":", "with", "node", ".", "stream", "(", ")", "as", "stream", ":", "for", "(", "lineno", ",", "line", ")", "in", "enumerate", "(", "stream", ")", ":", "if", "line", ".", "rstrip", "(", ")", ".", "endswith", "(", "\"\\\\\"", ")", ":", "self", ".", "add_message", "(", "\"backslash-line-continuation\"", ",", "line", "=", "lineno", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_env
Extracts the environment PYTHONPATH and appends the current sys.path to those.
pylint/epylint.py
def _get_env(): """Extracts the environment PYTHONPATH and appends the current sys.path to those.""" env = dict(os.environ) env["PYTHONPATH"] = os.pathsep.join(sys.path) return env
def _get_env(): """Extracts the environment PYTHONPATH and appends the current sys.path to those.""" env = dict(os.environ) env["PYTHONPATH"] = os.pathsep.join(sys.path) return env
[ "Extracts", "the", "environment", "PYTHONPATH", "and", "appends", "the", "current", "sys", ".", "path", "to", "those", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/epylint.py#L65-L70
[ "def", "_get_env", "(", ")", ":", "env", "=", "dict", "(", "os", ".", "environ", ")", "env", "[", "\"PYTHONPATH\"", "]", "=", "os", ".", "pathsep", ".", "join", "(", "sys", ".", "path", ")", "return", "env" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
lint
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)
pylint/epylint.py
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) child_path = osp.basename(full_path) while parent_path != "/" and osp.exists(osp.join(parent_path, "__init__.py")): child_path = osp.join(osp.basename(parent_path), child_path) parent_path = osp.dirname(parent_path) # Start pylint # Ensure we use the python and pylint associated with the running epylint run_cmd = "import sys; from pylint.lint import Run; Run(sys.argv[1:])" cmd = ( [sys.executable, "-c", run_cmd] + [ "--msg-template", "{path}:{line}: {category} ({msg_id}, {symbol}, {obj}) {msg}", "-r", "n", child_path, ] + list(options) ) process = Popen( cmd, stdout=PIPE, cwd=parent_path, env=_get_env(), universal_newlines=True ) for line in process.stdout: # remove pylintrc warning if line.startswith("No config file found"): continue # modify the file name thats output to reverse the path traversal we made parts = line.split(":") if parts and parts[0] == child_path: line = ":".join([filename] + parts[1:]) print(line, end=" ") process.wait() return process.returncode
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) child_path = osp.basename(full_path) while parent_path != "/" and osp.exists(osp.join(parent_path, "__init__.py")): child_path = osp.join(osp.basename(parent_path), child_path) parent_path = osp.dirname(parent_path) # Start pylint # Ensure we use the python and pylint associated with the running epylint run_cmd = "import sys; from pylint.lint import Run; Run(sys.argv[1:])" cmd = ( [sys.executable, "-c", run_cmd] + [ "--msg-template", "{path}:{line}: {category} ({msg_id}, {symbol}, {obj}) {msg}", "-r", "n", child_path, ] + list(options) ) process = Popen( cmd, stdout=PIPE, cwd=parent_path, env=_get_env(), universal_newlines=True ) for line in process.stdout: # remove pylintrc warning if line.startswith("No config file found"): continue # modify the file name thats output to reverse the path traversal we made parts = line.split(":") if parts and parts[0] == child_path: line = ":".join([filename] + parts[1:]) print(line, end=" ") process.wait() return process.returncode
[ "Pylint", "the", "given", "file", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/epylint.py#L73-L128
[ "def", "lint", "(", "filename", ",", "options", "=", "(", ")", ")", ":", "# traverse downwards until we are out of a python package", "full_path", "=", "osp", ".", "abspath", "(", "filename", ")", "parent_path", "=", "osp", ".", "dirname", "(", "full_path", ")", "child_path", "=", "osp", ".", "basename", "(", "full_path", ")", "while", "parent_path", "!=", "\"/\"", "and", "osp", ".", "exists", "(", "osp", ".", "join", "(", "parent_path", ",", "\"__init__.py\"", ")", ")", ":", "child_path", "=", "osp", ".", "join", "(", "osp", ".", "basename", "(", "parent_path", ")", ",", "child_path", ")", "parent_path", "=", "osp", ".", "dirname", "(", "parent_path", ")", "# Start pylint", "# Ensure we use the python and pylint associated with the running epylint", "run_cmd", "=", "\"import sys; from pylint.lint import Run; Run(sys.argv[1:])\"", "cmd", "=", "(", "[", "sys", ".", "executable", ",", "\"-c\"", ",", "run_cmd", "]", "+", "[", "\"--msg-template\"", ",", "\"{path}:{line}: {category} ({msg_id}, {symbol}, {obj}) {msg}\"", ",", "\"-r\"", ",", "\"n\"", ",", "child_path", ",", "]", "+", "list", "(", "options", ")", ")", "process", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "cwd", "=", "parent_path", ",", "env", "=", "_get_env", "(", ")", ",", "universal_newlines", "=", "True", ")", "for", "line", "in", "process", ".", "stdout", ":", "# remove pylintrc warning", "if", "line", ".", "startswith", "(", "\"No config file found\"", ")", ":", "continue", "# modify the file name thats output to reverse the path traversal we made", "parts", "=", "line", ".", "split", "(", "\":\"", ")", "if", "parts", "and", "parts", "[", "0", "]", "==", "child_path", ":", "line", "=", "\":\"", ".", "join", "(", "[", "filename", "]", "+", "parts", "[", "1", ":", "]", ")", "print", "(", "line", ",", "end", "=", "\" \"", ")", "process", ".", "wait", "(", ")", "return", "process", ".", "returncode" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
py_run
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)
pylint/epylint.py
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 call pylint epylint_part = [executable, "-c", "from pylint import epylint;epylint.Run()"] options = shlex.split(command_options, posix=not sys.platform.startswith("win")) cli = epylint_part + options # Providing standard output and/or error if not set if stdout is None: if return_std: stdout = PIPE else: stdout = sys.stdout if stderr is None: if return_std: stderr = PIPE else: stderr = sys.stderr # Call pylint in a subprocess process = Popen( cli, shell=False, stdout=stdout, stderr=stderr, env=_get_env(), universal_newlines=True, ) proc_stdout, proc_stderr = process.communicate() # Return standard output and error if return_std: return StringIO(proc_stdout), StringIO(proc_stderr) return None
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 call pylint epylint_part = [executable, "-c", "from pylint import epylint;epylint.Run()"] options = shlex.split(command_options, posix=not sys.platform.startswith("win")) cli = epylint_part + options # Providing standard output and/or error if not set if stdout is None: if return_std: stdout = PIPE else: stdout = sys.stdout if stderr is None: if return_std: stderr = PIPE else: stderr = sys.stderr # Call pylint in a subprocess process = Popen( cli, shell=False, stdout=stdout, stderr=stderr, env=_get_env(), universal_newlines=True, ) proc_stdout, proc_stderr = process.communicate() # Return standard output and error if return_std: return StringIO(proc_stdout), StringIO(proc_stderr) return None
[ "Run", "pylint", "from", "python" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/epylint.py#L131-L184
[ "def", "py_run", "(", "command_options", "=", "\"\"", ",", "return_std", "=", "False", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "# 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 call pylint", "epylint_part", "=", "[", "executable", ",", "\"-c\"", ",", "\"from pylint import epylint;epylint.Run()\"", "]", "options", "=", "shlex", ".", "split", "(", "command_options", ",", "posix", "=", "not", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ")", "cli", "=", "epylint_part", "+", "options", "# Providing standard output and/or error if not set", "if", "stdout", "is", "None", ":", "if", "return_std", ":", "stdout", "=", "PIPE", "else", ":", "stdout", "=", "sys", ".", "stdout", "if", "stderr", "is", "None", ":", "if", "return_std", ":", "stderr", "=", "PIPE", "else", ":", "stderr", "=", "sys", ".", "stderr", "# Call pylint in a subprocess", "process", "=", "Popen", "(", "cli", ",", "shell", "=", "False", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ",", "env", "=", "_get_env", "(", ")", ",", "universal_newlines", "=", "True", ",", ")", "proc_stdout", ",", "proc_stderr", "=", "process", ".", "communicate", "(", ")", "# Return standard output and error", "if", "return_std", ":", "return", "StringIO", "(", "proc_stdout", ")", ",", "StringIO", "(", "proc_stderr", ")", "return", "None" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
target_info_from_filename
Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png').
pylint/graph.py
def target_info_from_filename(filename): """Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png').""" basename = osp.basename(filename) storedir = osp.dirname(osp.abspath(filename)) target = filename.split(".")[-1] return storedir, basename, target
def target_info_from_filename(filename): """Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png').""" basename = osp.basename(filename) storedir = osp.dirname(osp.abspath(filename)) target = filename.split(".")[-1] return storedir, basename, target
[ "Transforms", "/", "some", "/", "path", "/", "foo", ".", "png", "into", "(", "/", "some", "/", "path", "foo", ".", "png", "png", ")", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L21-L26
[ "def", "target_info_from_filename", "(", "filename", ")", ":", "basename", "=", "osp", ".", "basename", "(", "filename", ")", "storedir", "=", "osp", ".", "dirname", "(", "osp", ".", "abspath", "(", "filename", ")", ")", "target", "=", "filename", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "return", "storedir", ",", "basename", ",", "target" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
get_cycles
given a dictionary representing an ordered graph (i.e. key are vertices and values is a list of destination vertices representing edges), return a list of detected cycles
pylint/graph.py
def get_cycles(graph_dict, vertices=None): """given a dictionary representing an ordered graph (i.e. key are vertices and values is a list of destination vertices representing edges), return a list of detected cycles """ if not graph_dict: return () result = [] if vertices is None: vertices = graph_dict.keys() for vertice in vertices: _get_cycles(graph_dict, [], set(), result, vertice) return result
def get_cycles(graph_dict, vertices=None): """given a dictionary representing an ordered graph (i.e. key are vertices and values is a list of destination vertices representing edges), return a list of detected cycles """ if not graph_dict: return () result = [] if vertices is None: vertices = graph_dict.keys() for vertice in vertices: _get_cycles(graph_dict, [], set(), result, vertice) return result
[ "given", "a", "dictionary", "representing", "an", "ordered", "graph", "(", "i", ".", "e", ".", "key", "are", "vertices", "and", "values", "is", "a", "list", "of", "destination", "vertices", "representing", "edges", ")", "return", "a", "list", "of", "detected", "cycles" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L158-L170
[ "def", "get_cycles", "(", "graph_dict", ",", "vertices", "=", "None", ")", ":", "if", "not", "graph_dict", ":", "return", "(", ")", "result", "=", "[", "]", "if", "vertices", "is", "None", ":", "vertices", "=", "graph_dict", ".", "keys", "(", ")", "for", "vertice", "in", "vertices", ":", "_get_cycles", "(", "graph_dict", ",", "[", "]", ",", "set", "(", ")", ",", "result", ",", "vertice", ")", "return", "result" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_cycles
recursive function doing the real work for get_cycles
pylint/graph.py
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) return path.append(vertice) try: for node in graph_dict[vertice]: # don't check already visited nodes again if node not in visited: _get_cycles(graph_dict, path, visited, result, node) visited.add(node) except KeyError: pass path.pop()
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) return path.append(vertice) try: for node in graph_dict[vertice]: # don't check already visited nodes again if node not in visited: _get_cycles(graph_dict, path, visited, result, node) visited.add(node) except KeyError: pass path.pop()
[ "recursive", "function", "doing", "the", "real", "work", "for", "get_cycles" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L173-L198
[ "def", "_get_cycles", "(", "graph_dict", ",", "path", ",", "visited", ",", "result", ",", "vertice", ")", ":", "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", ")", "return", "path", ".", "append", "(", "vertice", ")", "try", ":", "for", "node", "in", "graph_dict", "[", "vertice", "]", ":", "# don't check already visited nodes again", "if", "node", "not", "in", "visited", ":", "_get_cycles", "(", "graph_dict", ",", "path", ",", "visited", ",", "result", ",", "node", ")", "visited", ".", "add", "(", "node", ")", "except", "KeyError", ":", "pass", "path", ".", "pop", "(", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotBackend.get_source
returns self._source
pylint/graph.py
def get_source(self): """returns self._source""" if self._source is None: self.emit("}\n") self._source = "\n".join(self.lines) del self.lines return self._source
def get_source(self): """returns self._source""" if self._source is None: self.emit("}\n") self._source = "\n".join(self.lines) del self.lines return self._source
[ "returns", "self", ".", "_source" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L63-L69
[ "def", "get_source", "(", "self", ")", ":", "if", "self", ".", "_source", "is", "None", ":", "self", ".", "emit", "(", "\"}\\n\"", ")", "self", ".", "_source", "=", "\"\\n\"", ".", "join", "(", "self", ".", "lines", ")", "del", "self", ".", "lines", "return", "self", ".", "_source" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotBackend.generate
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
pylint/graph.py
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) pdot = codecs.open(dot_sourcepath, "w", encoding="utf8") pdot.write(self.source) pdot.close() if target != "dot": use_shell = sys.platform == "win32" if mapfile: subprocess.call( [ self.renderer, "-Tcmapx", "-o", mapfile, "-T", target, dot_sourcepath, "-o", outputfile, ], shell=use_shell, ) else: subprocess.call( [self.renderer, "-T", target, dot_sourcepath, "-o", outputfile], shell=use_shell, ) os.unlink(dot_sourcepath) return outputfile
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) pdot = codecs.open(dot_sourcepath, "w", encoding="utf8") pdot.write(self.source) pdot.close() if target != "dot": use_shell = sys.platform == "win32" if mapfile: subprocess.call( [ self.renderer, "-Tcmapx", "-o", mapfile, "-T", target, dot_sourcepath, "-o", outputfile, ], shell=use_shell, ) else: subprocess.call( [self.renderer, "-T", target, dot_sourcepath, "-o", outputfile], shell=use_shell, ) os.unlink(dot_sourcepath) return outputfile
[ "Generates", "a", "graph", "file", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L73-L131
[ "def", "generate", "(", "self", ",", "outputfile", "=", "None", ",", "dotfile", "=", "None", ",", "mapfile", "=", "None", ")", ":", "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", ")", "pdot", "=", "codecs", ".", "open", "(", "dot_sourcepath", ",", "\"w\"", ",", "encoding", "=", "\"utf8\"", ")", "pdot", ".", "write", "(", "self", ".", "source", ")", "pdot", ".", "close", "(", ")", "if", "target", "!=", "\"dot\"", ":", "use_shell", "=", "sys", ".", "platform", "==", "\"win32\"", "if", "mapfile", ":", "subprocess", ".", "call", "(", "[", "self", ".", "renderer", ",", "\"-Tcmapx\"", ",", "\"-o\"", ",", "mapfile", ",", "\"-T\"", ",", "target", ",", "dot_sourcepath", ",", "\"-o\"", ",", "outputfile", ",", "]", ",", "shell", "=", "use_shell", ",", ")", "else", ":", "subprocess", ".", "call", "(", "[", "self", ".", "renderer", ",", "\"-T\"", ",", "target", ",", "dot_sourcepath", ",", "\"-o\"", ",", "outputfile", "]", ",", "shell", "=", "use_shell", ",", ")", "os", ".", "unlink", "(", "dot_sourcepath", ")", "return", "outputfile" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotBackend.emit_edge
emit an edge from <name1> to <name2>. edge properties: see http://www.graphviz.org/doc/info/attrs.html
pylint/graph.py
def emit_edge(self, name1, name2, **props): """emit an edge from <name1> to <name2>. edge properties: see http://www.graphviz.org/doc/info/attrs.html """ attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()] n_from, n_to = normalize_node_id(name1), normalize_node_id(name2) self.emit("%s -> %s [%s];" % (n_from, n_to, ", ".join(sorted(attrs))))
def emit_edge(self, name1, name2, **props): """emit an edge from <name1> to <name2>. edge properties: see http://www.graphviz.org/doc/info/attrs.html """ attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()] n_from, n_to = normalize_node_id(name1), normalize_node_id(name2) self.emit("%s -> %s [%s];" % (n_from, n_to, ", ".join(sorted(attrs))))
[ "emit", "an", "edge", "from", "<name1", ">", "to", "<name2", ">", ".", "edge", "properties", ":", "see", "http", ":", "//", "www", ".", "graphviz", ".", "org", "/", "doc", "/", "info", "/", "attrs", ".", "html" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L137-L143
[ "def", "emit_edge", "(", "self", ",", "name1", ",", "name2", ",", "*", "*", "props", ")", ":", "attrs", "=", "[", "'%s=\"%s\"'", "%", "(", "prop", ",", "value", ")", "for", "prop", ",", "value", "in", "props", ".", "items", "(", ")", "]", "n_from", ",", "n_to", "=", "normalize_node_id", "(", "name1", ")", ",", "normalize_node_id", "(", "name2", ")", "self", ".", "emit", "(", "\"%s -> %s [%s];\"", "%", "(", "n_from", ",", "n_to", ",", "\", \"", ".", "join", "(", "sorted", "(", "attrs", ")", ")", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DotBackend.emit_node
emit a node with given properties. node properties: see http://www.graphviz.org/doc/info/attrs.html
pylint/graph.py
def emit_node(self, name, **props): """emit a node with given properties. node properties: see http://www.graphviz.org/doc/info/attrs.html """ attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()] self.emit("%s [%s];" % (normalize_node_id(name), ", ".join(sorted(attrs))))
def emit_node(self, name, **props): """emit a node with given properties. node properties: see http://www.graphviz.org/doc/info/attrs.html """ attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()] self.emit("%s [%s];" % (normalize_node_id(name), ", ".join(sorted(attrs))))
[ "emit", "a", "node", "with", "given", "properties", ".", "node", "properties", ":", "see", "http", ":", "//", "www", ".", "graphviz", ".", "org", "/", "doc", "/", "info", "/", "attrs", ".", "html" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/graph.py#L145-L150
[ "def", "emit_node", "(", "self", ",", "name", ",", "*", "*", "props", ")", ":", "attrs", "=", "[", "'%s=\"%s\"'", "%", "(", "prop", ",", "value", ")", "for", "prop", ",", "value", "in", "props", ".", "items", "(", ")", "]", "self", ".", "emit", "(", "\"%s [%s];\"", "%", "(", "normalize_node_id", "(", "name", ")", ",", "\", \"", ".", "join", "(", "sorted", "(", "attrs", ")", ")", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
report_raw_stats
calculate percentage of code / doc / comment / empty
pylint/checkers/raw_metrics.py
def report_raw_stats(sect, stats, _): """calculate percentage of code / doc / comment / empty """ total_lines = stats["total_lines"] if not total_lines: raise EmptyReportError() sect.description = "%s lines have been analyzed" % total_lines lines = ("type", "number", "%", "previous", "difference") for node_type in ("code", "docstring", "comment", "empty"): key = node_type + "_lines" total = stats[key] percent = float(total * 100) / total_lines lines += (node_type, str(total), "%.2f" % percent, "NC", "NC") sect.append(Table(children=lines, cols=5, rheaders=1))
def report_raw_stats(sect, stats, _): """calculate percentage of code / doc / comment / empty """ total_lines = stats["total_lines"] if not total_lines: raise EmptyReportError() sect.description = "%s lines have been analyzed" % total_lines lines = ("type", "number", "%", "previous", "difference") for node_type in ("code", "docstring", "comment", "empty"): key = node_type + "_lines" total = stats[key] percent = float(total * 100) / total_lines lines += (node_type, str(total), "%.2f" % percent, "NC", "NC") sect.append(Table(children=lines, cols=5, rheaders=1))
[ "calculate", "percentage", "of", "code", "/", "doc", "/", "comment", "/", "empty" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/raw_metrics.py#L27-L40
[ "def", "report_raw_stats", "(", "sect", ",", "stats", ",", "_", ")", ":", "total_lines", "=", "stats", "[", "\"total_lines\"", "]", "if", "not", "total_lines", ":", "raise", "EmptyReportError", "(", ")", "sect", ".", "description", "=", "\"%s lines have been analyzed\"", "%", "total_lines", "lines", "=", "(", "\"type\"", ",", "\"number\"", ",", "\"%\"", ",", "\"previous\"", ",", "\"difference\"", ")", "for", "node_type", "in", "(", "\"code\"", ",", "\"docstring\"", ",", "\"comment\"", ",", "\"empty\"", ")", ":", "key", "=", "node_type", "+", "\"_lines\"", "total", "=", "stats", "[", "key", "]", "percent", "=", "float", "(", "total", "*", "100", ")", "/", "total_lines", "lines", "+=", "(", "node_type", ",", "str", "(", "total", ")", ",", "\"%.2f\"", "%", "percent", ",", "\"NC\"", ",", "\"NC\"", ")", "sect", ".", "append", "(", "Table", "(", "children", "=", "lines", ",", "cols", "=", "5", ",", "rheaders", "=", "1", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
get_type
return the line type : docstring, comment, code, empty
pylint/checkers/raw_metrics.py
def get_type(tokens, start_index): """return the line type : docstring, comment, code, empty""" i = start_index tok_type = tokens[i][0] start = tokens[i][2] pos = start line_type = None while i < len(tokens) and tokens[i][2][0] == start[0]: tok_type = tokens[i][0] pos = tokens[i][3] if line_type is None: if tok_type == tokenize.STRING: line_type = "docstring_lines" elif tok_type == tokenize.COMMENT: line_type = "comment_lines" elif tok_type in JUNK: pass else: line_type = "code_lines" i += 1 if line_type is None: line_type = "empty_lines" elif i < len(tokens) and tokens[i][0] == tokenize.NEWLINE: i += 1 return i, pos[0] - start[0] + 1, line_type
def get_type(tokens, start_index): """return the line type : docstring, comment, code, empty""" i = start_index tok_type = tokens[i][0] start = tokens[i][2] pos = start line_type = None while i < len(tokens) and tokens[i][2][0] == start[0]: tok_type = tokens[i][0] pos = tokens[i][3] if line_type is None: if tok_type == tokenize.STRING: line_type = "docstring_lines" elif tok_type == tokenize.COMMENT: line_type = "comment_lines" elif tok_type in JUNK: pass else: line_type = "code_lines" i += 1 if line_type is None: line_type = "empty_lines" elif i < len(tokens) and tokens[i][0] == tokenize.NEWLINE: i += 1 return i, pos[0] - start[0] + 1, line_type
[ "return", "the", "line", "type", ":", "docstring", "comment", "code", "empty" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/raw_metrics.py#L90-L114
[ "def", "get_type", "(", "tokens", ",", "start_index", ")", ":", "i", "=", "start_index", "tok_type", "=", "tokens", "[", "i", "]", "[", "0", "]", "start", "=", "tokens", "[", "i", "]", "[", "2", "]", "pos", "=", "start", "line_type", "=", "None", "while", "i", "<", "len", "(", "tokens", ")", "and", "tokens", "[", "i", "]", "[", "2", "]", "[", "0", "]", "==", "start", "[", "0", "]", ":", "tok_type", "=", "tokens", "[", "i", "]", "[", "0", "]", "pos", "=", "tokens", "[", "i", "]", "[", "3", "]", "if", "line_type", "is", "None", ":", "if", "tok_type", "==", "tokenize", ".", "STRING", ":", "line_type", "=", "\"docstring_lines\"", "elif", "tok_type", "==", "tokenize", ".", "COMMENT", ":", "line_type", "=", "\"comment_lines\"", "elif", "tok_type", "in", "JUNK", ":", "pass", "else", ":", "line_type", "=", "\"code_lines\"", "i", "+=", "1", "if", "line_type", "is", "None", ":", "line_type", "=", "\"empty_lines\"", "elif", "i", "<", "len", "(", "tokens", ")", "and", "tokens", "[", "i", "]", "[", "0", "]", "==", "tokenize", ".", "NEWLINE", ":", "i", "+=", "1", "return", "i", ",", "pos", "[", "0", "]", "-", "start", "[", "0", "]", "+", "1", ",", "line_type" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RawMetricsChecker.open
init statistics
pylint/checkers/raw_metrics.py
def open(self): """init statistics""" self.stats = self.linter.add_stats( total_lines=0, code_lines=0, empty_lines=0, docstring_lines=0, comment_lines=0, )
def open(self): """init statistics""" self.stats = self.linter.add_stats( total_lines=0, code_lines=0, empty_lines=0, docstring_lines=0, comment_lines=0, )
[ "init", "statistics" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/raw_metrics.py#L67-L75
[ "def", "open", "(", "self", ")", ":", "self", ".", "stats", "=", "self", ".", "linter", ".", "add_stats", "(", "total_lines", "=", "0", ",", "code_lines", "=", "0", ",", "empty_lines", "=", "0", ",", "docstring_lines", "=", "0", ",", "comment_lines", "=", "0", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
RawMetricsChecker.process_tokens
update stats
pylint/checkers/raw_metrics.py
def process_tokens(self, tokens): """update stats""" i = 0 tokens = list(tokens) while i < len(tokens): i, lines_number, line_type = get_type(tokens, i) self.stats["total_lines"] += lines_number self.stats[line_type] += lines_number
def process_tokens(self, tokens): """update stats""" i = 0 tokens = list(tokens) while i < len(tokens): i, lines_number, line_type = get_type(tokens, i) self.stats["total_lines"] += lines_number self.stats[line_type] += lines_number
[ "update", "stats" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/raw_metrics.py#L77-L84
[ "def", "process_tokens", "(", "self", ",", "tokens", ")", ":", "i", "=", "0", "tokens", "=", "list", "(", "tokens", ")", "while", "i", "<", "len", "(", "tokens", ")", ":", "i", ",", "lines_number", ",", "line_type", "=", "get_type", "(", "tokens", ",", "i", ")", "self", ".", "stats", "[", "\"total_lines\"", "]", "+=", "lines_number", "self", ".", "stats", "[", "line_type", "]", "+=", "lines_number" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_rest_format_section
format an options section using as ReST formatted output
pylint/message/message_handler_mix_in.py
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) for optname, optdict, value in options: help_opt = optdict.get("help") print(":%s:" % optname, file=stream) if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent=" ") print(help_opt, file=stream) if value: value = str(_format_option_value(optdict, value)) print(file=stream) print(" Default: ``%s``" % value.replace("`` ", "```` ``"), file=stream)
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) for optname, optdict, value in options: help_opt = optdict.get("help") print(":%s:" % optname, file=stream) if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent=" ") print(help_opt, file=stream) if value: value = str(_format_option_value(optdict, value)) print(file=stream) print(" Default: ``%s``" % value.replace("`` ", "```` ``"), file=stream)
[ "format", "an", "options", "section", "using", "as", "ReST", "formatted", "output" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L33-L49
[ "def", "_rest_format_section", "(", "stream", ",", "section", ",", "options", ",", "doc", "=", "None", ")", ":", "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", ")", "for", "optname", ",", "optdict", ",", "value", "in", "options", ":", "help_opt", "=", "optdict", ".", "get", "(", "\"help\"", ")", "print", "(", "\":%s:\"", "%", "optname", ",", "file", "=", "stream", ")", "if", "help_opt", ":", "help_opt", "=", "normalize_text", "(", "help_opt", ",", "line_len", "=", "79", ",", "indent", "=", "\" \"", ")", "print", "(", "help_opt", ",", "file", "=", "stream", ")", "if", "value", ":", "value", "=", "str", "(", "_format_option_value", "(", "optdict", ",", "value", ")", ")", "print", "(", "file", "=", "stream", ")", "print", "(", "\" Default: ``%s``\"", "%", "value", ".", "replace", "(", "\"`` \"", ",", "\"```` ``\"", ")", ",", "file", "=", "stream", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn._register_by_id_managed_msg
If the msgid is a numeric one, then register it to inform the user it could furnish instead a symbolic msgid.
pylint/message/message_handler_mix_in.py
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( ( self.current_name, message_definition.msgid, message_definition.symbol, line, is_disabled, ) ) except UnknownMessageError: pass
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( ( self.current_name, message_definition.msgid, message_definition.symbol, line, is_disabled, ) ) except UnknownMessageError: pass
[ "If", "the", "msgid", "is", "a", "numeric", "one", "then", "register", "it", "to", "inform", "the", "user", "it", "could", "furnish", "instead", "a", "symbolic", "msgid", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L76-L93
[ "def", "_register_by_id_managed_msg", "(", "self", ",", "msgid", ",", "line", ",", "is_disabled", "=", "True", ")", ":", "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", "(", "(", "self", ".", "current_name", ",", "message_definition", ".", "msgid", ",", "message_definition", ".", "symbol", ",", "line", ",", "is_disabled", ",", ")", ")", "except", "UnknownMessageError", ":", "pass" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.disable
don't output message of the given id
pylint/message/message_handler_mix_in.py
def disable(self, msgid, scope="package", line=None, ignore_unknown=False): """don't output message of the given id""" self._set_msg_status( msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown ) self._register_by_id_managed_msg(msgid, line)
def disable(self, msgid, scope="package", line=None, ignore_unknown=False): """don't output message of the given id""" self._set_msg_status( msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown ) self._register_by_id_managed_msg(msgid, line)
[ "don", "t", "output", "message", "of", "the", "given", "id" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L95-L100
[ "def", "disable", "(", "self", ",", "msgid", ",", "scope", "=", "\"package\"", ",", "line", "=", "None", ",", "ignore_unknown", "=", "False", ")", ":", "self", ".", "_set_msg_status", "(", "msgid", ",", "enable", "=", "False", ",", "scope", "=", "scope", ",", "line", "=", "line", ",", "ignore_unknown", "=", "ignore_unknown", ")", "self", ".", "_register_by_id_managed_msg", "(", "msgid", ",", "line", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.enable
reenable message of the given id
pylint/message/message_handler_mix_in.py
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, ignore_unknown=ignore_unknown ) self._register_by_id_managed_msg(msgid, line, is_disabled=False)
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, ignore_unknown=ignore_unknown ) self._register_by_id_managed_msg(msgid, line, is_disabled=False)
[ "reenable", "message", "of", "the", "given", "id" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L102-L107
[ "def", "enable", "(", "self", ",", "msgid", ",", "scope", "=", "\"package\"", ",", "line", "=", "None", ",", "ignore_unknown", "=", "False", ")", ":", "self", ".", "_set_msg_status", "(", "msgid", ",", "enable", "=", "True", ",", "scope", "=", "scope", ",", "line", "=", "line", ",", "ignore_unknown", "=", "ignore_unknown", ")", "self", ".", "_register_by_id_managed_msg", "(", "msgid", ",", "line", ",", "is_disabled", "=", "False", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn._message_symbol
Get the message symbol of the given message id Return the original message id if the message does not exist.
pylint/message/message_handler_mix_in.py
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: return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] except UnknownMessageError: return msgid
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: return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] except UnknownMessageError: return msgid
[ "Get", "the", "message", "symbol", "of", "the", "given", "message", "id" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L176-L185
[ "def", "_message_symbol", "(", "self", ",", "msgid", ")", ":", "try", ":", "return", "[", "md", ".", "symbol", "for", "md", "in", "self", ".", "msgs_store", ".", "get_message_definitions", "(", "msgid", ")", "]", "except", "UnknownMessageError", ":", "return", "msgid" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.get_message_state_scope
Returns the scope at which a message was enabled/disabled.
pylint/message/message_handler_mix_in.py
def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED): """Returns the scope at which a message was enabled/disabled.""" if self.config.confidence and confidence.name not in self.config.confidence: return MSG_STATE_CONFIDENCE try: if line in self.file_state._module_msgs_state[msgid]: return MSG_STATE_SCOPE_MODULE except (KeyError, TypeError): return MSG_STATE_SCOPE_CONFIG return None
def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED): """Returns the scope at which a message was enabled/disabled.""" if self.config.confidence and confidence.name not in self.config.confidence: return MSG_STATE_CONFIDENCE try: if line in self.file_state._module_msgs_state[msgid]: return MSG_STATE_SCOPE_MODULE except (KeyError, TypeError): return MSG_STATE_SCOPE_CONFIG return None
[ "Returns", "the", "scope", "at", "which", "a", "message", "was", "enabled", "/", "disabled", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L187-L196
[ "def", "get_message_state_scope", "(", "self", ",", "msgid", ",", "line", "=", "None", ",", "confidence", "=", "UNDEFINED", ")", ":", "if", "self", ".", "config", ".", "confidence", "and", "confidence", ".", "name", "not", "in", "self", ".", "config", ".", "confidence", ":", "return", "MSG_STATE_CONFIDENCE", "try", ":", "if", "line", "in", "self", ".", "file_state", ".", "_module_msgs_state", "[", "msgid", "]", ":", "return", "MSG_STATE_SCOPE_MODULE", "except", "(", "KeyError", ",", "TypeError", ")", ":", "return", "MSG_STATE_SCOPE_CONFIG", "return", "None" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.is_message_enabled
return true if the message associated to the given message id is enabled msgid may be either a numeric or symbolic message id.
pylint/message/message_handler_mix_in.py
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 checks for messages that are not registered # due to version mismatch, just treat them as message IDs # for now. msgids = [msg_descr] for msgid in msgids: if self.is_one_message_enabled(msgid, line): return True return False
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 checks for messages that are not registered # due to version mismatch, just treat them as message IDs # for now. msgids = [msg_descr] for msgid in msgids: if self.is_one_message_enabled(msgid, line): return True return False
[ "return", "true", "if", "the", "message", "associated", "to", "the", "given", "message", "id", "is", "enabled" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L198-L218
[ "def", "is_message_enabled", "(", "self", ",", "msg_descr", ",", "line", "=", "None", ",", "confidence", "=", "None", ")", ":", "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 checks for messages that are not registered", "# due to version mismatch, just treat them as message IDs", "# for now.", "msgids", "=", "[", "msg_descr", "]", "for", "msgid", "in", "msgids", ":", "if", "self", ".", "is_one_message_enabled", "(", "msgid", ",", "line", ")", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.add_message
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 must provide the line argument.
pylint/message/message_handler_mix_in.py
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 must provide the line argument. """ message_definitions = self.msgs_store.get_message_definitions(msg_descr) for message_definition in message_definitions: self.add_one_message( message_definition, line, node, args, confidence, col_offset )
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 must provide the line argument. """ message_definitions = self.msgs_store.get_message_definitions(msg_descr) for message_definition in message_definitions: self.add_one_message( message_definition, line, node, args, confidence, col_offset )
[ "Adds", "a", "message", "given", "by", "ID", "or", "name", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L251-L272
[ "def", "add_message", "(", "self", ",", "msg_descr", ",", "line", "=", "None", ",", "node", "=", "None", ",", "args", "=", "None", ",", "confidence", "=", "UNDEFINED", ",", "col_offset", "=", "None", ",", ")", ":", "message_definitions", "=", "self", ".", "msgs_store", ".", "get_message_definitions", "(", "msg_descr", ")", "for", "message_definition", "in", "message_definitions", ":", "self", ".", "add_one_message", "(", "message_definition", ",", "line", ",", "node", ",", "args", ",", "confidence", ",", "col_offset", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn.print_full_documentation
output a full documentation in ReST format
pylint/message/message_handler_mix_in.py
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), } print("Pylint checkers' options and switches", file=stream) print("-------------------------------------", file=stream) print("", file=stream) print("Pylint checkers can provide three set of features:", file=stream) print("", file=stream) print("* options that control their execution,", file=stream) print("* messages that they can raise,", file=stream) print("* reports that they can generate.", file=stream) print("", file=stream) print("Below is a list of all checkers and their features.", file=stream) print("", file=stream) for checker, info in sorted(by_checker.items()): self._print_checker_doc(checker, info, stream=stream)
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), } print("Pylint checkers' options and switches", file=stream) print("-------------------------------------", file=stream) print("", file=stream) print("Pylint checkers can provide three set of features:", file=stream) print("", file=stream) print("* options that control their execution,", file=stream) print("* messages that they can raise,", file=stream) print("* reports that they can generate.", file=stream) print("", file=stream) print("Below is a list of all checkers and their features.", file=stream) print("", file=stream) for checker, info in sorted(by_checker.items()): self._print_checker_doc(checker, info, stream=stream)
[ "output", "a", "full", "documentation", "in", "ReST", "format" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L350-L400
[ "def", "print_full_documentation", "(", "self", ",", "stream", "=", "None", ")", ":", "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", ")", ",", "}", "print", "(", "\"Pylint checkers' options and switches\"", ",", "file", "=", "stream", ")", "print", "(", "\"-------------------------------------\"", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "print", "(", "\"Pylint checkers can provide three set of features:\"", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "print", "(", "\"* options that control their execution,\"", ",", "file", "=", "stream", ")", "print", "(", "\"* messages that they can raise,\"", ",", "file", "=", "stream", ")", "print", "(", "\"* reports that they can generate.\"", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "print", "(", "\"Below is a list of all checkers and their features.\"", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "for", "checker", ",", "info", "in", "sorted", "(", "by_checker", ".", "items", "(", ")", ")", ":", "self", ".", "_print_checker_doc", "(", "checker", ",", "info", ",", "stream", "=", "stream", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
MessagesHandlerMixIn._print_checker_doc
Helper method for print_full_documentation. Also used by doc/exts/pylint_extensions.py.
pylint/message/message_handler_mix_in.py
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) print(title, file=stream) print("^" * len(title), file=stream) _rest_format_section(stream, None, options) print("", file=stream) if msgs: title = "{} Messages".format(checker_title) print(title, file=stream) print("^" * len(title), file=stream) for msgid, msg in sorted( msgs.items(), key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1]) ): msg = build_message_definition(checker_name, msgid, msg) print(msg.format_help(checkerref=False), file=stream) print("", file=stream) if reports: title = "{} Reports".format(checker_title) print(title, file=stream) print("^" * len(title), file=stream) for report in reports: print(":%s: %s" % report[:2], file=stream) print("", file=stream) print("", file=stream)
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) print(title, file=stream) print("^" * len(title), file=stream) _rest_format_section(stream, None, options) print("", file=stream) if msgs: title = "{} Messages".format(checker_title) print(title, file=stream) print("^" * len(title), file=stream) for msgid, msg in sorted( msgs.items(), key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1]) ): msg = build_message_definition(checker_name, msgid, msg) print(msg.format_help(checkerref=False), file=stream) print("", file=stream) if reports: title = "{} Reports".format(checker_title) print(title, file=stream) print("^" * len(title), file=stream) for report in reports: print(":%s: %s" % report[:2], file=stream) print("", file=stream) print("", file=stream)
[ "Helper", "method", "for", "print_full_documentation", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L403-L459
[ "def", "_print_checker_doc", "(", "checker_name", ",", "info", ",", "stream", "=", "None", ")", ":", "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", ")", "print", "(", "title", ",", "file", "=", "stream", ")", "print", "(", "\"^\"", "*", "len", "(", "title", ")", ",", "file", "=", "stream", ")", "_rest_format_section", "(", "stream", ",", "None", ",", "options", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "if", "msgs", ":", "title", "=", "\"{} Messages\"", ".", "format", "(", "checker_title", ")", "print", "(", "title", ",", "file", "=", "stream", ")", "print", "(", "\"^\"", "*", "len", "(", "title", ")", ",", "file", "=", "stream", ")", "for", "msgid", ",", "msg", "in", "sorted", "(", "msgs", ".", "items", "(", ")", ",", "key", "=", "lambda", "kv", ":", "(", "_MSG_ORDER", ".", "index", "(", "kv", "[", "0", "]", "[", "0", "]", ")", ",", "kv", "[", "1", "]", ")", ")", ":", "msg", "=", "build_message_definition", "(", "checker_name", ",", "msgid", ",", "msg", ")", "print", "(", "msg", ".", "format_help", "(", "checkerref", "=", "False", ")", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "if", "reports", ":", "title", "=", "\"{} Reports\"", ".", "format", "(", "checker_title", ")", "print", "(", "title", ",", "file", "=", "stream", ")", "print", "(", "\"^\"", "*", "len", "(", "title", ")", ",", "file", "=", "stream", ")", "for", "report", "in", "reports", ":", "print", "(", "\":%s: %s\"", "%", "report", "[", ":", "2", "]", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")", "print", "(", "\"\"", ",", "file", "=", "stream", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_indent_length
Return the length of the indentation on the given token's line.
pylint/checkers/format.py
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 elif char == "\t": result += _TAB_LENGTH else: break return result
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 elif char == "\t": result += _TAB_LENGTH else: break return result
[ "Return", "the", "length", "of", "the", "indentation", "on", "the", "given", "token", "s", "line", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L260-L270
[ "def", "_get_indent_length", "(", "line", ")", ":", "result", "=", "0", "for", "char", "in", "line", ":", "if", "char", "==", "\" \"", ":", "result", "+=", "1", "elif", "char", "==", "\"\\t\"", ":", "result", "+=", "_TAB_LENGTH", "else", ":", "break", "return", "result" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_indent_hint_line
Return a line with |s for each of the positions in the given lists.
pylint/checkers/format.py
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 > bad_position else "remove" delta_message = _CONTINUATION_HINT_MESSAGE % ( direction, delta, "s" if delta > 1 else "", ) markers.append((bad_position, "^")) markers.sort() line = [" "] * (markers[-1][0] + 1) for position, marker in markers: line[position] = marker return ("".join(line), delta_message)
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 > bad_position else "remove" delta_message = _CONTINUATION_HINT_MESSAGE % ( direction, delta, "s" if delta > 1 else "", ) markers.append((bad_position, "^")) markers.sort() line = [" "] * (markers[-1][0] + 1) for position, marker in markers: line[position] = marker return ("".join(line), delta_message)
[ "Return", "a", "line", "with", "|s", "for", "each", "of", "the", "positions", "in", "the", "given", "lists", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L273-L297
[ "def", "_get_indent_hint_line", "(", "bar_positions", ",", "bad_position", ")", ":", "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", ">", "bad_position", "else", "\"remove\"", "delta_message", "=", "_CONTINUATION_HINT_MESSAGE", "%", "(", "direction", ",", "delta", ",", "\"s\"", "if", "delta", ">", "1", "else", "\"\"", ",", ")", "markers", ".", "append", "(", "(", "bad_position", ",", "\"^\"", ")", ")", "markers", ".", "sort", "(", ")", "line", "=", "[", "\" \"", "]", "*", "(", "markers", "[", "-", "1", "]", "[", "0", "]", "+", "1", ")", "for", "position", ",", "marker", "in", "markers", ":", "line", "[", "position", "]", "=", "marker", "return", "(", "\"\"", ".", "join", "(", "line", ")", ",", "delta_message", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
TokenWrapper.token_indent
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)" is "<TAB><TAB> "
pylint/checkers/format.py
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)" is "<TAB><TAB> " """ line_indent = self.line_indent(idx) return line_indent + " " * (self.start_col(idx) - len(line_indent))
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)" is "<TAB><TAB> " """ line_indent = self.line_indent(idx) return line_indent + " " * (self.start_col(idx) - len(line_indent))
[ "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", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L393-L402
[ "def", "token_indent", "(", "self", ",", "idx", ")", ":", "line_indent", "=", "self", ".", "line_indent", "(", "idx", ")", "return", "line_indent", "+", "\" \"", "*", "(", "self", ".", "start_col", "(", "idx", ")", "-", "len", "(", "line_indent", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ContinuedLineState.handle_line_start
Record the first non-junk token at the start of a line.
pylint/checkers/format.py
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 self._is_block_opener = ( self._tokens.token(check_token_position) in _CONTINUATION_BLOCK_OPENERS ) self._line_start = pos
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 self._is_block_opener = ( self._tokens.token(check_token_position) in _CONTINUATION_BLOCK_OPENERS ) self._line_start = pos
[ "Record", "the", "first", "non", "-", "junk", "token", "at", "the", "start", "of", "a", "line", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L432-L443
[ "def", "handle_line_start", "(", "self", ",", "pos", ")", ":", "if", "self", ".", "_line_start", ">", "-", "1", ":", "return", "check_token_position", "=", "pos", "if", "self", ".", "_tokens", ".", "token", "(", "pos", ")", "==", "_ASYNC_TOKEN", ":", "check_token_position", "+=", "1", "self", ".", "_is_block_opener", "=", "(", "self", ".", "_tokens", ".", "token", "(", "check_token_position", ")", "in", "_CONTINUATION_BLOCK_OPENERS", ")", "self", ".", "_line_start", "=", "pos" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ContinuedLineState.get_valid_indentations
Returns the valid offsets for the token at the given position.
pylint/checkers/format.py
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 = self._cont_stack[stack_top] if self._tokens.token(idx) in _CLOSING_BRACKETS: valid_indentations = indent.valid_outdent_strings else: valid_indentations = indent.valid_continuation_strings return indent, valid_indentations.copy()
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 = self._cont_stack[stack_top] if self._tokens.token(idx) in _CLOSING_BRACKETS: valid_indentations = indent.valid_outdent_strings else: valid_indentations = indent.valid_continuation_strings return indent, valid_indentations.copy()
[ "Returns", "the", "valid", "offsets", "for", "the", "token", "at", "the", "given", "position", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L462-L477
[ "def", "get_valid_indentations", "(", "self", ",", "idx", ")", ":", "# 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", "=", "self", ".", "_cont_stack", "[", "stack_top", "]", "if", "self", ".", "_tokens", ".", "token", "(", "idx", ")", "in", "_CLOSING_BRACKETS", ":", "valid_indentations", "=", "indent", ".", "valid_outdent_strings", "else", ":", "valid_indentations", "=", "indent", ".", "valid_continuation_strings", "return", "indent", ",", "valid_indentations", ".", "copy", "(", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ContinuedLineState._hanging_indent_after_bracket
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
pylint/checkers/format.py
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 # current indent level paren_align = self._cont_stack[-1].valid_outdent_strings next_align = self._cont_stack[-1].valid_continuation_strings.copy() next_align_keys = list(next_align.keys()) next_align[next_align_keys[0] + self._continuation_string] = True # Note that the continuation of # d = { # 'a': 'b' # 'c' # } # is handled by the special-casing for hanging continued string indents. return _ContinuedIndent( HANGING_DICT_VALUE, bracket, position, paren_align, next_align ) return _ContinuedIndent( HANGING, bracket, position, _Indentations(indentation, indentation + self._continuation_string), _Indentations(indentation + self._continuation_string), )
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 # current indent level paren_align = self._cont_stack[-1].valid_outdent_strings next_align = self._cont_stack[-1].valid_continuation_strings.copy() next_align_keys = list(next_align.keys()) next_align[next_align_keys[0] + self._continuation_string] = True # Note that the continuation of # d = { # 'a': 'b' # 'c' # } # is handled by the special-casing for hanging continued string indents. return _ContinuedIndent( HANGING_DICT_VALUE, bracket, position, paren_align, next_align ) return _ContinuedIndent( HANGING, bracket, position, _Indentations(indentation, indentation + self._continuation_string), _Indentations(indentation + self._continuation_string), )
[ "Extracts", "indentation", "information", "for", "a", "hanging", "indent" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L479-L528
[ "def", "_hanging_indent_after_bracket", "(", "self", ",", "bracket", ",", "position", ")", ":", "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", "# current indent level", "paren_align", "=", "self", ".", "_cont_stack", "[", "-", "1", "]", ".", "valid_outdent_strings", "next_align", "=", "self", ".", "_cont_stack", "[", "-", "1", "]", ".", "valid_continuation_strings", ".", "copy", "(", ")", "next_align_keys", "=", "list", "(", "next_align", ".", "keys", "(", ")", ")", "next_align", "[", "next_align_keys", "[", "0", "]", "+", "self", ".", "_continuation_string", "]", "=", "True", "# Note that the continuation of", "# d = {", "# 'a': 'b'", "# 'c'", "# }", "# is handled by the special-casing for hanging continued string indents.", "return", "_ContinuedIndent", "(", "HANGING_DICT_VALUE", ",", "bracket", ",", "position", ",", "paren_align", ",", "next_align", ")", "return", "_ContinuedIndent", "(", "HANGING", ",", "bracket", ",", "position", ",", "_Indentations", "(", "indentation", ",", "indentation", "+", "self", ".", "_continuation_string", ")", ",", "_Indentations", "(", "indentation", "+", "self", ".", "_continuation_string", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ContinuedLineState._continuation_inside_bracket
Extracts indentation information for a continued indent.
pylint/checkers/format.py
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 ): return _ContinuedIndent( CONTINUED_BLOCK, bracket, position, _Indentations(token_indent), _BeforeBlockIndentations( next_token_indent, next_token_indent + self._continuation_string ), ) return _ContinuedIndent( CONTINUED, bracket, position, _Indentations(token_indent, next_token_indent), _Indentations(next_token_indent), )
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 ): return _ContinuedIndent( CONTINUED_BLOCK, bracket, position, _Indentations(token_indent), _BeforeBlockIndentations( next_token_indent, next_token_indent + self._continuation_string ), ) return _ContinuedIndent( CONTINUED, bracket, position, _Indentations(token_indent, next_token_indent), _Indentations(next_token_indent), )
[ "Extracts", "indentation", "information", "for", "a", "continued", "indent", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L530-L554
[ "def", "_continuation_inside_bracket", "(", "self", ",", "bracket", ",", "position", ")", ":", "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", ")", ":", "return", "_ContinuedIndent", "(", "CONTINUED_BLOCK", ",", "bracket", ",", "position", ",", "_Indentations", "(", "token_indent", ")", ",", "_BeforeBlockIndentations", "(", "next_token_indent", ",", "next_token_indent", "+", "self", ".", "_continuation_string", ")", ",", ")", "return", "_ContinuedIndent", "(", "CONTINUED", ",", "bracket", ",", "position", ",", "_Indentations", "(", "token_indent", ",", "next_token_indent", ")", ",", "_Indentations", "(", "next_token_indent", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ContinuedLineState.push_token
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 those interesting tokens. :param int token: The concrete token :param int position: The position of the token in the stream.
pylint/checkers/format.py
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 those interesting tokens. :param int token: The concrete token :param int position: The position of the token in the stream. """ if _token_followed_by_eol(self._tokens, position): self._cont_stack.append(self._hanging_indent_after_bracket(token, position)) else: self._cont_stack.append(self._continuation_inside_bracket(token, position))
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 those interesting tokens. :param int token: The concrete token :param int position: The position of the token in the stream. """ if _token_followed_by_eol(self._tokens, position): self._cont_stack.append(self._hanging_indent_after_bracket(token, position)) else: self._cont_stack.append(self._continuation_inside_bracket(token, position))
[ "Pushes", "a", "new", "token", "for", "continued", "indentation", "on", "the", "stack", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L559-L576
[ "def", "push_token", "(", "self", ",", "token", ",", "position", ")", ":", "if", "_token_followed_by_eol", "(", "self", ".", "_tokens", ",", "position", ")", ":", "self", ".", "_cont_stack", ".", "append", "(", "self", ".", "_hanging_indent_after_bracket", "(", "token", ",", "position", ")", ")", "else", ":", "self", ".", "_cont_stack", ".", "append", "(", "self", ".", "_continuation_inside_bracket", "(", "token", ",", "position", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker.new_line
a new line has been encountered, process it if necessary
pylint/checkers/format.py
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) line = tokens.line(line_start) if tokens.type(line_start) not in _JUNK_TOKENS: self._lines[line_num] = line.split("\n")[0] self.check_lines(line, line_num)
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) line = tokens.line(line_start) if tokens.type(line_start) not in _JUNK_TOKENS: self._lines[line_num] = line.split("\n")[0] self.check_lines(line, line_num)
[ "a", "new", "line", "has", "been", "encountered", "process", "it", "if", "necessary" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L716-L725
[ "def", "new_line", "(", "self", ",", "tokens", ",", "line_end", ",", "line_start", ")", ":", "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", ")", "line", "=", "tokens", ".", "line", "(", "line_start", ")", "if", "tokens", ".", "type", "(", "line_start", ")", "not", "in", "_JUNK_TOKENS", ":", "self", ".", "_lines", "[", "line_num", "]", "=", "line", ".", "split", "(", "\"\\n\"", ")", "[", "0", "]", "self", ".", "check_lines", "(", "line", ",", "line_num", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker._check_keyword_parentheses
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.
pylint/checkers/format.py
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 ) elif keyword_token in ("return", "yield"): self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif keyword_token not in self._keywords_with_parens: if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) return elif depth == 1: # This is a tuple, which is always acceptable. if token[1] == ",": return # 'and' and 'or' are the only boolean operators with lower precedence # than 'not', so parens are only required when they are found. if token[1] in ("and", "or"): found_and_or = True # A yield inside an expression must always be in parentheses, # quit early without error. elif token[1] == "yield": return # A generator expression always has a 'for' token in it, and # the 'for' token is only legal inside parens when it is in a # generator expression. The parens are necessary here, so bail # without an error. elif token[1] == "for": return
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 ) elif keyword_token in ("return", "yield"): self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif keyword_token not in self._keywords_with_parens: if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) return elif depth == 1: # This is a tuple, which is always acceptable. if token[1] == ",": return # 'and' and 'or' are the only boolean operators with lower precedence # than 'not', so parens are only required when they are found. if token[1] in ("and", "or"): found_and_or = True # A yield inside an expression must always be in parentheses, # quit early without error. elif token[1] == "yield": return # A generator expression always has a 'for' token in it, and # the 'for' token is only legal inside parens when it is in a # generator expression. The parens are necessary here, so bail # without an error. elif token[1] == "for": return
[ "Check", "that", "there", "are", "not", "unnecessary", "parens", "after", "a", "keyword", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L730-L804
[ "def", "_check_keyword_parentheses", "(", "self", ",", "tokens", ",", "start", ")", ":", "# 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", ")", "elif", "keyword_token", "in", "(", "\"return\"", ",", "\"yield\"", ")", ":", "self", ".", "add_message", "(", "\"superfluous-parens\"", ",", "line", "=", "line_num", ",", "args", "=", "keyword_token", ")", "elif", "keyword_token", "not", "in", "self", ".", "_keywords_with_parens", ":", "if", "not", "found_and_or", ":", "self", ".", "add_message", "(", "\"superfluous-parens\"", ",", "line", "=", "line_num", ",", "args", "=", "keyword_token", ")", "return", "elif", "depth", "==", "1", ":", "# This is a tuple, which is always acceptable.", "if", "token", "[", "1", "]", "==", "\",\"", ":", "return", "# 'and' and 'or' are the only boolean operators with lower precedence", "# than 'not', so parens are only required when they are found.", "if", "token", "[", "1", "]", "in", "(", "\"and\"", ",", "\"or\"", ")", ":", "found_and_or", "=", "True", "# A yield inside an expression must always be in parentheses,", "# quit early without error.", "elif", "token", "[", "1", "]", "==", "\"yield\"", ":", "return", "# A generator expression always has a 'for' token in it, and", "# the 'for' token is only legal inside parens when it is in a", "# generator expression. The parens are necessary here, so bail", "# without an error.", "elif", "token", "[", "1", "]", "==", "\"for\"", ":", "return" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker._has_valid_type_annotation
Extended check of PEP-484 type hint presence
pylint/checkers/format.py
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] == ":": return True if token[1] == "(": return False if token[1] == "]": bracket_level += 1 elif token[1] == "[": bracket_level -= 1 elif token[1] == ",": if not bracket_level: return False elif token[1] in (".", "..."): continue elif token[0] not in (tokenize.NAME, tokenize.STRING, tokenize.NL): return False return False
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] == ":": return True if token[1] == "(": return False if token[1] == "]": bracket_level += 1 elif token[1] == "[": bracket_level -= 1 elif token[1] == ",": if not bracket_level: return False elif token[1] in (".", "..."): continue elif token[0] not in (tokenize.NAME, tokenize.STRING, tokenize.NL): return False return False
[ "Extended", "check", "of", "PEP", "-", "484", "type", "hint", "presence" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L835-L859
[ "def", "_has_valid_type_annotation", "(", "self", ",", "tokens", ",", "i", ")", ":", "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", "]", "==", "\":\"", ":", "return", "True", "if", "token", "[", "1", "]", "==", "\"(\"", ":", "return", "False", "if", "token", "[", "1", "]", "==", "\"]\"", ":", "bracket_level", "+=", "1", "elif", "token", "[", "1", "]", "==", "\"[\"", ":", "bracket_level", "-=", "1", "elif", "token", "[", "1", "]", "==", "\",\"", ":", "if", "not", "bracket_level", ":", "return", "False", "elif", "token", "[", "1", "]", "in", "(", "\".\"", ",", "\"...\"", ")", ":", "continue", "elif", "token", "[", "0", "]", "not", "in", "(", "tokenize", ".", "NAME", ",", "tokenize", ".", "STRING", ",", "tokenize", ".", "NL", ")", ":", "return", "False", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker._check_equals_spacing
Check the spacing of a single equals sign.
pylint/checkers/format.py
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"): self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT)) else: self._check_space(tokens, i, (_MUST, _MUST))
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"): self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT)) else: self._check_space(tokens, i, (_MUST, _MUST))
[ "Check", "the", "spacing", "of", "a", "single", "equals", "sign", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L861-L868
[ "def", "_check_equals_spacing", "(", "self", ",", "tokens", ",", "i", ")", ":", "if", "self", ".", "_has_valid_type_annotation", "(", "tokens", ",", "i", ")", ":", "self", ".", "_check_space", "(", "tokens", ",", "i", ",", "(", "_MUST", ",", "_MUST", ")", ")", "elif", "self", ".", "_inside_brackets", "(", "\"(\"", ")", "or", "self", ".", "_inside_brackets", "(", "\"lambda\"", ")", ":", "self", ".", "_check_space", "(", "tokens", ",", "i", ",", "(", "_MUST_NOT", ",", "_MUST_NOT", ")", ")", "else", ":", "self", ".", "_check_space", "(", "tokens", ",", "i", ",", "(", "_MUST", ",", "_MUST", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker._check_surrounded_by_space
Check that a binary operator is surrounded by exactly one space.
pylint/checkers/format.py
def _check_surrounded_by_space(self, tokens, i): """Check that a binary operator is surrounded by exactly one space.""" self._check_space(tokens, i, (_MUST, _MUST))
def _check_surrounded_by_space(self, tokens, i): """Check that a binary operator is surrounded by exactly one space.""" self._check_space(tokens, i, (_MUST, _MUST))
[ "Check", "that", "a", "binary", "operator", "is", "surrounded", "by", "exactly", "one", "space", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L898-L900
[ "def", "_check_surrounded_by_space", "(", "self", ",", "tokens", ",", "i", ")", ":", "self", ".", "_check_space", "(", "tokens", ",", "i", ",", "(", "_MUST", ",", "_MUST", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker.process_tokens
process tokens and search for : _ non strict indentation (i.e. not always using the <indent> parameter as indent unit) _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression).
pylint/checkers/format.py
def process_tokens(self, tokens): """process tokens and search for : _ non strict indentation (i.e. not always using the <indent> parameter as indent unit) _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 self._current_line = ContinuedLineState(tokens, self.config) for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = True self._process_retained_warnings(TokenWrapper(tokens), idx) self._current_line.next_logical_line() self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num self._check_continued_indentation(TokenWrapper(tokens), idx + 1) self._current_line.next_physical_line() elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): self._current_line.handle_line_start(idx) # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next(filter(None, map(self.linter._pragma_lineno.get, names)), 1) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num)
def process_tokens(self, tokens): """process tokens and search for : _ non strict indentation (i.e. not always using the <indent> parameter as indent unit) _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 self._current_line = ContinuedLineState(tokens, self.config) for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = True self._process_retained_warnings(TokenWrapper(tokens), idx) self._current_line.next_logical_line() self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num self._check_continued_indentation(TokenWrapper(tokens), idx + 1) self._current_line.next_physical_line() elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): self._current_line.handle_line_start(idx) # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next(filter(None, map(self.linter._pragma_lineno.get, names)), 1) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num)
[ "process", "tokens", "and", "search", "for", ":" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L974-L1072
[ "def", "process_tokens", "(", "self", ",", "tokens", ")", ":", "self", ".", "_bracket_stack", "=", "[", "None", "]", "indents", "=", "[", "0", "]", "check_equal", "=", "False", "line_num", "=", "0", "self", ".", "_lines", "=", "{", "}", "self", ".", "_visited_lines", "=", "{", "}", "token_handlers", "=", "self", ".", "_prepare_token_dispatcher", "(", ")", "self", ".", "_last_line_ending", "=", "None", "last_blank_line_num", "=", "0", "self", ".", "_current_line", "=", "ContinuedLineState", "(", "tokens", ",", "self", ".", "config", ")", "for", "idx", ",", "(", "tok_type", ",", "token", ",", "start", ",", "_", ",", "line", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "start", "[", "0", "]", "!=", "line_num", ":", "line_num", "=", "start", "[", "0", "]", "# A tokenizer oddity: if an indented line contains a multi-line", "# docstring, the line member of the INDENT token does not contain", "# the full line; therefore we check the next token on the line.", "if", "tok_type", "==", "tokenize", ".", "INDENT", ":", "self", ".", "new_line", "(", "TokenWrapper", "(", "tokens", ")", ",", "idx", "-", "1", ",", "idx", "+", "1", ")", "else", ":", "self", ".", "new_line", "(", "TokenWrapper", "(", "tokens", ")", ",", "idx", "-", "1", ",", "idx", ")", "if", "tok_type", "==", "tokenize", ".", "NEWLINE", ":", "# a program statement, or ENDMARKER, will eventually follow,", "# after some (possibly empty) run of tokens of the form", "# (NL | COMMENT)* (INDENT | DEDENT+)?", "# If an INDENT appears, setting check_equal is wrong, and will", "# be undone when we see the INDENT.", "check_equal", "=", "True", "self", ".", "_process_retained_warnings", "(", "TokenWrapper", "(", "tokens", ")", ",", "idx", ")", "self", ".", "_current_line", ".", "next_logical_line", "(", ")", "self", ".", "_check_line_ending", "(", "token", ",", "line_num", ")", "elif", "tok_type", "==", "tokenize", ".", "INDENT", ":", "check_equal", "=", "False", "self", ".", "check_indent_level", "(", "token", ",", "indents", "[", "-", "1", "]", "+", "1", ",", "line_num", ")", "indents", ".", "append", "(", "indents", "[", "-", "1", "]", "+", "1", ")", "elif", "tok_type", "==", "tokenize", ".", "DEDENT", ":", "# there's nothing we need to check here! what's important is", "# that when the run of DEDENTs ends, the indentation of the", "# program statement (or ENDMARKER) that triggered the run is", "# equal to what's left at the top of the indents stack", "check_equal", "=", "True", "if", "len", "(", "indents", ")", ">", "1", ":", "del", "indents", "[", "-", "1", "]", "elif", "tok_type", "==", "tokenize", ".", "NL", ":", "if", "not", "line", ".", "strip", "(", "\"\\r\\n\"", ")", ":", "last_blank_line_num", "=", "line_num", "self", ".", "_check_continued_indentation", "(", "TokenWrapper", "(", "tokens", ")", ",", "idx", "+", "1", ")", "self", ".", "_current_line", ".", "next_physical_line", "(", ")", "elif", "tok_type", "not", "in", "(", "tokenize", ".", "COMMENT", ",", "tokenize", ".", "ENCODING", ")", ":", "self", ".", "_current_line", ".", "handle_line_start", "(", "idx", ")", "# This is the first concrete token following a NEWLINE, so it", "# must be the first token of the next program statement, or an", "# ENDMARKER; the \"line\" argument exposes the leading whitespace", "# for this statement; in the case of ENDMARKER, line is an empty", "# string, so will properly match the empty string with which the", "# \"indents\" stack was seeded", "if", "check_equal", ":", "check_equal", "=", "False", "self", ".", "check_indent_level", "(", "line", ",", "indents", "[", "-", "1", "]", ",", "line_num", ")", "if", "tok_type", "==", "tokenize", ".", "NUMBER", "and", "token", ".", "endswith", "(", "\"l\"", ")", ":", "self", ".", "add_message", "(", "\"lowercase-l-suffix\"", ",", "line", "=", "line_num", ")", "try", ":", "handler", "=", "token_handlers", "[", "token", "]", "except", "KeyError", ":", "pass", "else", ":", "handler", "(", "tokens", ",", "idx", ")", "line_num", "-=", "1", "# to be ok with \"wc -l\"", "if", "line_num", ">", "self", ".", "config", ".", "max_module_lines", ":", "# Get the line where the too-many-lines (or its message id)", "# was disabled or default to 1.", "message_definition", "=", "self", ".", "linter", ".", "msgs_store", ".", "get_message_definitions", "(", "\"too-many-lines\"", ")", "[", "0", "]", "names", "=", "(", "message_definition", ".", "msgid", ",", "\"too-many-lines\"", ")", "line", "=", "next", "(", "filter", "(", "None", ",", "map", "(", "self", ".", "linter", ".", "_pragma_lineno", ".", "get", ",", "names", ")", ")", ",", "1", ")", "self", ".", "add_message", "(", "\"too-many-lines\"", ",", "args", "=", "(", "line_num", ",", "self", ".", "config", ".", "max_module_lines", ")", ",", "line", "=", "line", ",", ")", "# See if there are any trailing lines. Do not complain about empty", "# files like __init__.py markers.", "if", "line_num", "==", "last_blank_line_num", "and", "line_num", ">", "0", ":", "self", ".", "add_message", "(", "\"trailing-newlines\"", ",", "line", "=", "line_num", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600