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
FormatChecker.visit_default
check the node line number and check it if not yet done
pylint/checkers/format.py
def visit_default(self, node): """check the node line number and check it if not yet done""" if not node.is_statement: return if not node.root().pure_python: return # XXX block visit of child nodes prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno else: # The line on which a finally: occurs in a try/finally # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: if ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 else: prev_line = node.parent.statement().fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("")
def visit_default(self, node): """check the node line number and check it if not yet done""" if not node.is_statement: return if not node.root().pure_python: return # XXX block visit of child nodes prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno else: # The line on which a finally: occurs in a try/finally # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: if ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 else: prev_line = node.parent.statement().fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("")
[ "check", "the", "node", "line", "number", "and", "check", "it", "if", "not", "yet", "done" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L1166-L1205
[ "def", "visit_default", "(", "self", ",", "node", ")", ":", "if", "not", "node", ".", "is_statement", ":", "return", "if", "not", "node", ".", "root", "(", ")", ".", "pure_python", ":", "return", "# XXX block visit of child nodes", "prev_sibl", "=", "node", ".", "previous_sibling", "(", ")", "if", "prev_sibl", "is", "not", "None", ":", "prev_line", "=", "prev_sibl", ".", "fromlineno", "else", ":", "# The line on which a finally: occurs in a try/finally", "# is not directly represented in the AST. We infer it", "# by taking the last line of the body and adding 1, which", "# should be the line of finally:", "if", "(", "isinstance", "(", "node", ".", "parent", ",", "nodes", ".", "TryFinally", ")", "and", "node", "in", "node", ".", "parent", ".", "finalbody", ")", ":", "prev_line", "=", "node", ".", "parent", ".", "body", "[", "0", "]", ".", "tolineno", "+", "1", "else", ":", "prev_line", "=", "node", ".", "parent", ".", "statement", "(", ")", ".", "fromlineno", "line", "=", "node", ".", "fromlineno", "assert", "line", ",", "node", "if", "prev_line", "==", "line", "and", "self", ".", "_visited_lines", ".", "get", "(", "line", ")", "!=", "2", ":", "self", ".", "_check_multi_statement_line", "(", "node", ",", "line", ")", "return", "if", "line", "in", "self", ".", "_visited_lines", ":", "return", "try", ":", "tolineno", "=", "node", ".", "blockstart_tolineno", "except", "AttributeError", ":", "tolineno", "=", "node", ".", "tolineno", "assert", "tolineno", ",", "node", "lines", "=", "[", "]", "for", "line", "in", "range", "(", "line", ",", "tolineno", "+", "1", ")", ":", "self", ".", "_visited_lines", "[", "line", "]", "=", "1", "try", ":", "lines", ".", "append", "(", "self", ".", "_lines", "[", "line", "]", ".", "rstrip", "(", ")", ")", "except", "KeyError", ":", "lines", ".", "append", "(", "\"\"", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker._check_multi_statement_line
Check for lines containing multiple statements.
pylint/checkers/format.py
def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2
def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2
[ "Check", "for", "lines", "containing", "multiple", "statements", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L1207-L1232
[ "def", "_check_multi_statement_line", "(", "self", ",", "node", ",", "line", ")", ":", "# Do not warn about multiple nested context managers", "# in with statements.", "if", "isinstance", "(", "node", ",", "nodes", ".", "With", ")", ":", "return", "# For try... except... finally..., the two nodes", "# appear to be on the same line due to how the AST is built.", "if", "isinstance", "(", "node", ",", "nodes", ".", "TryExcept", ")", "and", "isinstance", "(", "node", ".", "parent", ",", "nodes", ".", "TryFinally", ")", ":", "return", "if", "(", "isinstance", "(", "node", ".", "parent", ",", "nodes", ".", "If", ")", "and", "not", "node", ".", "parent", ".", "orelse", "and", "self", ".", "config", ".", "single_line_if_stmt", ")", ":", "return", "if", "(", "isinstance", "(", "node", ".", "parent", ",", "nodes", ".", "ClassDef", ")", "and", "len", "(", "node", ".", "parent", ".", "body", ")", "==", "1", "and", "self", ".", "config", ".", "single_line_class_stmt", ")", ":", "return", "self", ".", "add_message", "(", "\"multiple-statements\"", ",", "node", "=", "node", ")", "self", ".", "_visited_lines", "[", "line", "]", "=", "2" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker.check_lines
check lines have less than a maximum number of characters
pylint/checkers/format.py
def check_lines(self, lines, i): """check lines have less than a maximum number of characters """ max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines def check_line(line, i): if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) else: # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if not stripped_line and _EMPTY_LINE in self.config.no_space_check: # allow empty lines pass elif line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) # Don't count excess whitespace in the line length. line = stripped_line mobj = OPTION_RGX.search(line) if mobj and "=" in line: front_of_equal, _, back_of_equal = mobj.group(1).partition("=") if front_of_equal.strip() == "disable": if "line-too-long" in { _msg_id.strip() for _msg_id in back_of_equal.split(",") }: return None line = line.rsplit("#", 1)[0].rstrip() if len(line) > max_chars and not ignore_long_line.search(line): self.add_message("line-too-long", line=i, args=(len(line), max_chars)) return i + 1 unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } unsplit = [] for line in lines.splitlines(True): if line[-1] in unsplit_ends: unsplit.append(line) continue if unsplit: unsplit.append(line) line = "".join(unsplit) unsplit = [] i = check_line(line, i) if i is None: break if unsplit: check_line("".join(unsplit), i)
def check_lines(self, lines, i): """check lines have less than a maximum number of characters """ max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines def check_line(line, i): if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) else: # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if not stripped_line and _EMPTY_LINE in self.config.no_space_check: # allow empty lines pass elif line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) # Don't count excess whitespace in the line length. line = stripped_line mobj = OPTION_RGX.search(line) if mobj and "=" in line: front_of_equal, _, back_of_equal = mobj.group(1).partition("=") if front_of_equal.strip() == "disable": if "line-too-long" in { _msg_id.strip() for _msg_id in back_of_equal.split(",") }: return None line = line.rsplit("#", 1)[0].rstrip() if len(line) > max_chars and not ignore_long_line.search(line): self.add_message("line-too-long", line=i, args=(len(line), max_chars)) return i + 1 unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } unsplit = [] for line in lines.splitlines(True): if line[-1] in unsplit_ends: unsplit.append(line) continue if unsplit: unsplit.append(line) line = "".join(unsplit) unsplit = [] i = check_line(line, i) if i is None: break if unsplit: check_line("".join(unsplit), i)
[ "check", "lines", "have", "less", "than", "a", "maximum", "number", "of", "characters" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L1234-L1297
[ "def", "check_lines", "(", "self", ",", "lines", ",", "i", ")", ":", "max_chars", "=", "self", ".", "config", ".", "max_line_length", "ignore_long_line", "=", "self", ".", "config", ".", "ignore_long_lines", "def", "check_line", "(", "line", ",", "i", ")", ":", "if", "not", "line", ".", "endswith", "(", "\"\\n\"", ")", ":", "self", ".", "add_message", "(", "\"missing-final-newline\"", ",", "line", "=", "i", ")", "else", ":", "# exclude \\f (formfeed) from the rstrip", "stripped_line", "=", "line", ".", "rstrip", "(", "\"\\t\\n\\r\\v \"", ")", "if", "not", "stripped_line", "and", "_EMPTY_LINE", "in", "self", ".", "config", ".", "no_space_check", ":", "# allow empty lines", "pass", "elif", "line", "[", "len", "(", "stripped_line", ")", ":", "]", "not", "in", "(", "\"\\n\"", ",", "\"\\r\\n\"", ")", ":", "self", ".", "add_message", "(", "\"trailing-whitespace\"", ",", "line", "=", "i", ",", "col_offset", "=", "len", "(", "stripped_line", ")", ")", "# Don't count excess whitespace in the line length.", "line", "=", "stripped_line", "mobj", "=", "OPTION_RGX", ".", "search", "(", "line", ")", "if", "mobj", "and", "\"=\"", "in", "line", ":", "front_of_equal", ",", "_", ",", "back_of_equal", "=", "mobj", ".", "group", "(", "1", ")", ".", "partition", "(", "\"=\"", ")", "if", "front_of_equal", ".", "strip", "(", ")", "==", "\"disable\"", ":", "if", "\"line-too-long\"", "in", "{", "_msg_id", ".", "strip", "(", ")", "for", "_msg_id", "in", "back_of_equal", ".", "split", "(", "\",\"", ")", "}", ":", "return", "None", "line", "=", "line", ".", "rsplit", "(", "\"#\"", ",", "1", ")", "[", "0", "]", ".", "rstrip", "(", ")", "if", "len", "(", "line", ")", ">", "max_chars", "and", "not", "ignore_long_line", ".", "search", "(", "line", ")", ":", "self", ".", "add_message", "(", "\"line-too-long\"", ",", "line", "=", "i", ",", "args", "=", "(", "len", "(", "line", ")", ",", "max_chars", ")", ")", "return", "i", "+", "1", "unsplit_ends", "=", "{", "\"\\v\"", ",", "\"\\x0b\"", ",", "\"\\f\"", ",", "\"\\x0c\"", ",", "\"\\x1c\"", ",", "\"\\x1d\"", ",", "\"\\x1e\"", ",", "\"\\x85\"", ",", "\"\\u2028\"", ",", "\"\\u2029\"", ",", "}", "unsplit", "=", "[", "]", "for", "line", "in", "lines", ".", "splitlines", "(", "True", ")", ":", "if", "line", "[", "-", "1", "]", "in", "unsplit_ends", ":", "unsplit", ".", "append", "(", "line", ")", "continue", "if", "unsplit", ":", "unsplit", ".", "append", "(", "line", ")", "line", "=", "\"\"", ".", "join", "(", "unsplit", ")", "unsplit", "=", "[", "]", "i", "=", "check_line", "(", "line", ",", "i", ")", "if", "i", "is", "None", ":", "break", "if", "unsplit", ":", "check_line", "(", "\"\"", ".", "join", "(", "unsplit", ")", ",", "i", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
FormatChecker.check_indent_level
return the indent level of the string
pylint/checkers/format.py
def check_indent_level(self, string, expected, line_num): """return the indent level of the string """ indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": if string[0] != indent[0]: if string[0] == "\t": args = ("tab", "space") else: args = ("space", "tab") self.add_message("mixed-indentation", args=args, line=line_num) return level suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), ) return None
def check_indent_level(self, string, expected, line_num): """return the indent level of the string """ indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": if string[0] != indent[0]: if string[0] == "\t": args = ("tab", "space") else: args = ("space", "tab") self.add_message("mixed-indentation", args=args, line=line_num) return level suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), ) return None
[ "return", "the", "indent", "level", "of", "the", "string" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/format.py#L1299-L1330
[ "def", "check_indent_level", "(", "self", ",", "string", ",", "expected", ",", "line_num", ")", ":", "indent", "=", "self", ".", "config", ".", "indent_string", "if", "indent", "==", "\"\\\\t\"", ":", "# \\t is not interpreted in the configuration file", "indent", "=", "\"\\t\"", "level", "=", "0", "unit_size", "=", "len", "(", "indent", ")", "while", "string", "[", ":", "unit_size", "]", "==", "indent", ":", "string", "=", "string", "[", "unit_size", ":", "]", "level", "+=", "1", "suppl", "=", "\"\"", "while", "string", "and", "string", "[", "0", "]", "in", "\" \\t\"", ":", "if", "string", "[", "0", "]", "!=", "indent", "[", "0", "]", ":", "if", "string", "[", "0", "]", "==", "\"\\t\"", ":", "args", "=", "(", "\"tab\"", ",", "\"space\"", ")", "else", ":", "args", "=", "(", "\"space\"", ",", "\"tab\"", ")", "self", ".", "add_message", "(", "\"mixed-indentation\"", ",", "args", "=", "args", ",", "line", "=", "line_num", ")", "return", "level", "suppl", "+=", "string", "[", "0", "]", "string", "=", "string", "[", "1", ":", "]", "if", "level", "!=", "expected", "or", "suppl", ":", "i_type", "=", "\"spaces\"", "if", "indent", "[", "0", "]", "==", "\"\\t\"", ":", "i_type", "=", "\"tabs\"", "self", ".", "add_message", "(", "\"bad-indentation\"", ",", "line", "=", "line_num", ",", "args", "=", "(", "level", "*", "unit_size", "+", "len", "(", "suppl", ")", ",", "i_type", ",", "expected", "*", "unit_size", ")", ",", ")", "return", "None" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_in_iterating_context
Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context().
pylint/checkers/python3.py
def _in_iterating_context(node): """Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context(). """ parent = node.parent # Since a call can't be the loop variant we only need to know if the node's # parent is a 'for' loop to know it's being used as the iterator for the # loop. if isinstance(parent, astroid.For): return True # Need to make sure the use of the node is in the iterator part of the # comprehension. if isinstance(parent, astroid.Comprehension): if parent.iter == node: return True # Various built-ins can take in an iterable or list and lead to the same # value. elif isinstance(parent, astroid.Call): if isinstance(parent.func, astroid.Name): parent_scope = parent.func.lookup(parent.func.name)[0] if _is_builtin(parent_scope) and parent.func.name in _ACCEPTS_ITERATOR: return True elif isinstance(parent.func, astroid.Attribute): if parent.func.attrname in ATTRIBUTES_ACCEPTS_ITERATOR: return True inferred = utils.safe_infer(parent.func) if inferred: if inferred.qname() in _BUILTIN_METHOD_ACCEPTS_ITERATOR: return True root = inferred.root() if root and root.name == "itertools": return True # If the call is in an unpacking, there's no need to warn, # since it can be considered iterating. elif isinstance(parent, astroid.Assign) and isinstance( parent.targets[0], (astroid.List, astroid.Tuple) ): if len(parent.targets[0].elts) > 1: return True # If the call is in a containment check, we consider that to # be an iterating context elif ( isinstance(parent, astroid.Compare) and len(parent.ops) == 1 and parent.ops[0][0] == "in" ): return True # Also if it's an `yield from`, that's fair elif isinstance(parent, astroid.YieldFrom): return True if isinstance(parent, astroid.Starred): return True return False
def _in_iterating_context(node): """Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context(). """ parent = node.parent # Since a call can't be the loop variant we only need to know if the node's # parent is a 'for' loop to know it's being used as the iterator for the # loop. if isinstance(parent, astroid.For): return True # Need to make sure the use of the node is in the iterator part of the # comprehension. if isinstance(parent, astroid.Comprehension): if parent.iter == node: return True # Various built-ins can take in an iterable or list and lead to the same # value. elif isinstance(parent, astroid.Call): if isinstance(parent.func, astroid.Name): parent_scope = parent.func.lookup(parent.func.name)[0] if _is_builtin(parent_scope) and parent.func.name in _ACCEPTS_ITERATOR: return True elif isinstance(parent.func, astroid.Attribute): if parent.func.attrname in ATTRIBUTES_ACCEPTS_ITERATOR: return True inferred = utils.safe_infer(parent.func) if inferred: if inferred.qname() in _BUILTIN_METHOD_ACCEPTS_ITERATOR: return True root = inferred.root() if root and root.name == "itertools": return True # If the call is in an unpacking, there's no need to warn, # since it can be considered iterating. elif isinstance(parent, astroid.Assign) and isinstance( parent.targets[0], (astroid.List, astroid.Tuple) ): if len(parent.targets[0].elts) > 1: return True # If the call is in a containment check, we consider that to # be an iterating context elif ( isinstance(parent, astroid.Compare) and len(parent.ops) == 1 and parent.ops[0][0] == "in" ): return True # Also if it's an `yield from`, that's fair elif isinstance(parent, astroid.YieldFrom): return True if isinstance(parent, astroid.Starred): return True return False
[ "Check", "if", "the", "node", "is", "being", "used", "as", "an", "iterator", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L96-L150
[ "def", "_in_iterating_context", "(", "node", ")", ":", "parent", "=", "node", ".", "parent", "# Since a call can't be the loop variant we only need to know if the node's", "# parent is a 'for' loop to know it's being used as the iterator for the", "# loop.", "if", "isinstance", "(", "parent", ",", "astroid", ".", "For", ")", ":", "return", "True", "# Need to make sure the use of the node is in the iterator part of the", "# comprehension.", "if", "isinstance", "(", "parent", ",", "astroid", ".", "Comprehension", ")", ":", "if", "parent", ".", "iter", "==", "node", ":", "return", "True", "# Various built-ins can take in an iterable or list and lead to the same", "# value.", "elif", "isinstance", "(", "parent", ",", "astroid", ".", "Call", ")", ":", "if", "isinstance", "(", "parent", ".", "func", ",", "astroid", ".", "Name", ")", ":", "parent_scope", "=", "parent", ".", "func", ".", "lookup", "(", "parent", ".", "func", ".", "name", ")", "[", "0", "]", "if", "_is_builtin", "(", "parent_scope", ")", "and", "parent", ".", "func", ".", "name", "in", "_ACCEPTS_ITERATOR", ":", "return", "True", "elif", "isinstance", "(", "parent", ".", "func", ",", "astroid", ".", "Attribute", ")", ":", "if", "parent", ".", "func", ".", "attrname", "in", "ATTRIBUTES_ACCEPTS_ITERATOR", ":", "return", "True", "inferred", "=", "utils", ".", "safe_infer", "(", "parent", ".", "func", ")", "if", "inferred", ":", "if", "inferred", ".", "qname", "(", ")", "in", "_BUILTIN_METHOD_ACCEPTS_ITERATOR", ":", "return", "True", "root", "=", "inferred", ".", "root", "(", ")", "if", "root", "and", "root", ".", "name", "==", "\"itertools\"", ":", "return", "True", "# If the call is in an unpacking, there's no need to warn,", "# since it can be considered iterating.", "elif", "isinstance", "(", "parent", ",", "astroid", ".", "Assign", ")", "and", "isinstance", "(", "parent", ".", "targets", "[", "0", "]", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ")", ")", ":", "if", "len", "(", "parent", ".", "targets", "[", "0", "]", ".", "elts", ")", ">", "1", ":", "return", "True", "# If the call is in a containment check, we consider that to", "# be an iterating context", "elif", "(", "isinstance", "(", "parent", ",", "astroid", ".", "Compare", ")", "and", "len", "(", "parent", ".", "ops", ")", "==", "1", "and", "parent", ".", "ops", "[", "0", "]", "[", "0", "]", "==", "\"in\"", ")", ":", "return", "True", "# Also if it's an `yield from`, that's fair", "elif", "isinstance", "(", "parent", ",", "astroid", ".", "YieldFrom", ")", ":", "return", "True", "if", "isinstance", "(", "parent", ",", "astroid", ".", "Starred", ")", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_conditional_import
Checks if an import node is in the context of a conditional.
pylint/checkers/python3.py
def _is_conditional_import(node): """Checks if an import node is in the context of a conditional. """ parent = node.parent return isinstance( parent, (astroid.TryExcept, astroid.ExceptHandler, astroid.If, astroid.IfExp) )
def _is_conditional_import(node): """Checks if an import node is in the context of a conditional. """ parent = node.parent return isinstance( parent, (astroid.TryExcept, astroid.ExceptHandler, astroid.If, astroid.IfExp) )
[ "Checks", "if", "an", "import", "node", "is", "in", "the", "context", "of", "a", "conditional", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L153-L159
[ "def", "_is_conditional_import", "(", "node", ")", ":", "parent", "=", "node", ".", "parent", "return", "isinstance", "(", "parent", ",", "(", "astroid", ".", "TryExcept", ",", "astroid", ".", "ExceptHandler", ",", "astroid", ".", "If", ",", "astroid", ".", "IfExp", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Python3Checker.visit_name
Detect when a "bad" built-in is referenced.
pylint/checkers/python3.py
def visit_name(self, node): """Detect when a "bad" built-in is referenced.""" found_node, _ = node.lookup(node.name) if not _is_builtin(found_node): return if node.name not in self._bad_builtins: return if node_ignores_exception(node) or isinstance( find_try_except_wrapper_node(node), astroid.ExceptHandler ): return message = node.name.lower() + "-builtin" self.add_message(message, node=node)
def visit_name(self, node): """Detect when a "bad" built-in is referenced.""" found_node, _ = node.lookup(node.name) if not _is_builtin(found_node): return if node.name not in self._bad_builtins: return if node_ignores_exception(node) or isinstance( find_try_except_wrapper_node(node), astroid.ExceptHandler ): return message = node.name.lower() + "-builtin" self.add_message(message, node=node)
[ "Detect", "when", "a", "bad", "built", "-", "in", "is", "referenced", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L1001-L1014
[ "def", "visit_name", "(", "self", ",", "node", ")", ":", "found_node", ",", "_", "=", "node", ".", "lookup", "(", "node", ".", "name", ")", "if", "not", "_is_builtin", "(", "found_node", ")", ":", "return", "if", "node", ".", "name", "not", "in", "self", ".", "_bad_builtins", ":", "return", "if", "node_ignores_exception", "(", "node", ")", "or", "isinstance", "(", "find_try_except_wrapper_node", "(", "node", ")", ",", "astroid", ".", "ExceptHandler", ")", ":", "return", "message", "=", "node", ".", "name", ".", "lower", "(", ")", "+", "\"-builtin\"", "self", ".", "add_message", "(", "message", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Python3Checker.visit_subscript
Look for indexing exceptions.
pylint/checkers/python3.py
def visit_subscript(self, node): """ Look for indexing exceptions. """ try: for inferred in node.value.infer(): if not isinstance(inferred, astroid.Instance): continue if utils.inherit_from_std_ex(inferred): self.add_message("indexing-exception", node=node) except astroid.InferenceError: return
def visit_subscript(self, node): """ Look for indexing exceptions. """ try: for inferred in node.value.infer(): if not isinstance(inferred, astroid.Instance): continue if utils.inherit_from_std_ex(inferred): self.add_message("indexing-exception", node=node) except astroid.InferenceError: return
[ "Look", "for", "indexing", "exceptions", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L1226-L1235
[ "def", "visit_subscript", "(", "self", ",", "node", ")", ":", "try", ":", "for", "inferred", "in", "node", ".", "value", ".", "infer", "(", ")", ":", "if", "not", "isinstance", "(", "inferred", ",", "astroid", ".", "Instance", ")", ":", "continue", "if", "utils", ".", "inherit_from_std_ex", "(", "inferred", ")", ":", "self", ".", "add_message", "(", "\"indexing-exception\"", ",", "node", "=", "node", ")", "except", "astroid", ".", "InferenceError", ":", "return" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Python3Checker.visit_attribute
Look for removed attributes
pylint/checkers/python3.py
def visit_attribute(self, node): """Look for removed attributes""" if node.attrname == "xreadlines": self.add_message("xreadlines-attribute", node=node) return exception_message = "message" try: for inferred in node.expr.infer(): if isinstance(inferred, astroid.Instance) and utils.inherit_from_std_ex( inferred ): if node.attrname == exception_message: # Exceptions with .message clearly defined are an exception if exception_message in inferred.instance_attrs: continue self.add_message("exception-message-attribute", node=node) if isinstance(inferred, astroid.Module): self._warn_if_deprecated( node, inferred.name, {node.attrname}, report_on_modules=False ) except astroid.InferenceError: return
def visit_attribute(self, node): """Look for removed attributes""" if node.attrname == "xreadlines": self.add_message("xreadlines-attribute", node=node) return exception_message = "message" try: for inferred in node.expr.infer(): if isinstance(inferred, astroid.Instance) and utils.inherit_from_std_ex( inferred ): if node.attrname == exception_message: # Exceptions with .message clearly defined are an exception if exception_message in inferred.instance_attrs: continue self.add_message("exception-message-attribute", node=node) if isinstance(inferred, astroid.Module): self._warn_if_deprecated( node, inferred.name, {node.attrname}, report_on_modules=False ) except astroid.InferenceError: return
[ "Look", "for", "removed", "attributes" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L1245-L1268
[ "def", "visit_attribute", "(", "self", ",", "node", ")", ":", "if", "node", ".", "attrname", "==", "\"xreadlines\"", ":", "self", ".", "add_message", "(", "\"xreadlines-attribute\"", ",", "node", "=", "node", ")", "return", "exception_message", "=", "\"message\"", "try", ":", "for", "inferred", "in", "node", ".", "expr", ".", "infer", "(", ")", ":", "if", "isinstance", "(", "inferred", ",", "astroid", ".", "Instance", ")", "and", "utils", ".", "inherit_from_std_ex", "(", "inferred", ")", ":", "if", "node", ".", "attrname", "==", "exception_message", ":", "# Exceptions with .message clearly defined are an exception", "if", "exception_message", "in", "inferred", ".", "instance_attrs", ":", "continue", "self", ".", "add_message", "(", "\"exception-message-attribute\"", ",", "node", "=", "node", ")", "if", "isinstance", "(", "inferred", ",", "astroid", ".", "Module", ")", ":", "self", ".", "_warn_if_deprecated", "(", "node", ",", "inferred", ".", "name", ",", "{", "node", ".", "attrname", "}", ",", "report_on_modules", "=", "False", ")", "except", "astroid", ".", "InferenceError", ":", "return" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Python3Checker.visit_excepthandler
Visit an except handler block and check for exception unpacking.
pylint/checkers/python3.py
def visit_excepthandler(self, node): """Visit an except handler block and check for exception unpacking.""" def _is_used_in_except_block(node): scope = node.scope() current = node while ( current and current != scope and not isinstance(current, astroid.ExceptHandler) ): current = current.parent return isinstance(current, astroid.ExceptHandler) and current.type != node if isinstance(node.name, (astroid.Tuple, astroid.List)): self.add_message("unpacking-in-except", node=node) return if not node.name: return # Find any names scope = node.parent.scope() scope_names = scope.nodes_of_class(astroid.Name, skip_klass=astroid.FunctionDef) scope_names = list(scope_names) potential_leaked_names = [ scope_name for scope_name in scope_names if scope_name.name == node.name.name and scope_name.lineno > node.lineno and not _is_used_in_except_block(scope_name) ] reassignments_for_same_name = { assign_name.lineno for assign_name in scope.nodes_of_class( astroid.AssignName, skip_klass=astroid.FunctionDef ) if assign_name.name == node.name.name } for leaked_name in potential_leaked_names: if any( node.lineno < elem < leaked_name.lineno for elem in reassignments_for_same_name ): continue self.add_message("exception-escape", node=leaked_name)
def visit_excepthandler(self, node): """Visit an except handler block and check for exception unpacking.""" def _is_used_in_except_block(node): scope = node.scope() current = node while ( current and current != scope and not isinstance(current, astroid.ExceptHandler) ): current = current.parent return isinstance(current, astroid.ExceptHandler) and current.type != node if isinstance(node.name, (astroid.Tuple, astroid.List)): self.add_message("unpacking-in-except", node=node) return if not node.name: return # Find any names scope = node.parent.scope() scope_names = scope.nodes_of_class(astroid.Name, skip_klass=astroid.FunctionDef) scope_names = list(scope_names) potential_leaked_names = [ scope_name for scope_name in scope_names if scope_name.name == node.name.name and scope_name.lineno > node.lineno and not _is_used_in_except_block(scope_name) ] reassignments_for_same_name = { assign_name.lineno for assign_name in scope.nodes_of_class( astroid.AssignName, skip_klass=astroid.FunctionDef ) if assign_name.name == node.name.name } for leaked_name in potential_leaked_names: if any( node.lineno < elem < leaked_name.lineno for elem in reassignments_for_same_name ): continue self.add_message("exception-escape", node=leaked_name)
[ "Visit", "an", "except", "handler", "block", "and", "check", "for", "exception", "unpacking", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L1271-L1316
[ "def", "visit_excepthandler", "(", "self", ",", "node", ")", ":", "def", "_is_used_in_except_block", "(", "node", ")", ":", "scope", "=", "node", ".", "scope", "(", ")", "current", "=", "node", "while", "(", "current", "and", "current", "!=", "scope", "and", "not", "isinstance", "(", "current", ",", "astroid", ".", "ExceptHandler", ")", ")", ":", "current", "=", "current", ".", "parent", "return", "isinstance", "(", "current", ",", "astroid", ".", "ExceptHandler", ")", "and", "current", ".", "type", "!=", "node", "if", "isinstance", "(", "node", ".", "name", ",", "(", "astroid", ".", "Tuple", ",", "astroid", ".", "List", ")", ")", ":", "self", ".", "add_message", "(", "\"unpacking-in-except\"", ",", "node", "=", "node", ")", "return", "if", "not", "node", ".", "name", ":", "return", "# Find any names", "scope", "=", "node", ".", "parent", ".", "scope", "(", ")", "scope_names", "=", "scope", ".", "nodes_of_class", "(", "astroid", ".", "Name", ",", "skip_klass", "=", "astroid", ".", "FunctionDef", ")", "scope_names", "=", "list", "(", "scope_names", ")", "potential_leaked_names", "=", "[", "scope_name", "for", "scope_name", "in", "scope_names", "if", "scope_name", ".", "name", "==", "node", ".", "name", ".", "name", "and", "scope_name", ".", "lineno", ">", "node", ".", "lineno", "and", "not", "_is_used_in_except_block", "(", "scope_name", ")", "]", "reassignments_for_same_name", "=", "{", "assign_name", ".", "lineno", "for", "assign_name", "in", "scope", ".", "nodes_of_class", "(", "astroid", ".", "AssignName", ",", "skip_klass", "=", "astroid", ".", "FunctionDef", ")", "if", "assign_name", ".", "name", "==", "node", ".", "name", ".", "name", "}", "for", "leaked_name", "in", "potential_leaked_names", ":", "if", "any", "(", "node", ".", "lineno", "<", "elem", "<", "leaked_name", ".", "lineno", "for", "elem", "in", "reassignments_for_same_name", ")", ":", "continue", "self", ".", "add_message", "(", "\"exception-escape\"", ",", "node", "=", "leaked_name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
Python3Checker.visit_raise
Visit a raise statement and check for raising strings or old-raise-syntax.
pylint/checkers/python3.py
def visit_raise(self, node): """Visit a raise statement and check for raising strings or old-raise-syntax. """ # Ignore empty raise. if node.exc is None: return expr = node.exc if self._check_raise_value(node, expr): return try: value = next(astroid.unpack_infer(expr)) except astroid.InferenceError: return self._check_raise_value(node, value)
def visit_raise(self, node): """Visit a raise statement and check for raising strings or old-raise-syntax. """ # Ignore empty raise. if node.exc is None: return expr = node.exc if self._check_raise_value(node, expr): return try: value = next(astroid.unpack_infer(expr)) except astroid.InferenceError: return self._check_raise_value(node, value)
[ "Visit", "a", "raise", "statement", "and", "check", "for", "raising", "strings", "or", "old", "-", "raise", "-", "syntax", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/python3.py#L1323-L1338
[ "def", "visit_raise", "(", "self", ",", "node", ")", ":", "# Ignore empty raise.", "if", "node", ".", "exc", "is", "None", ":", "return", "expr", "=", "node", ".", "exc", "if", "self", ".", "_check_raise_value", "(", "node", ",", "expr", ")", ":", "return", "try", ":", "value", "=", "next", "(", "astroid", ".", "unpack_infer", "(", "expr", ")", ")", "except", "astroid", ".", "InferenceError", ":", "return", "self", ".", "_check_raise_value", "(", "node", ",", "value", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
find_pylintrc
search the pylint rc file and return its path if it find it, else None
pylint/config.py
def find_pylintrc(): """search the pylint rc file and return its path if it find it, else None """ # is there a pylint rc file in the current directory ? if os.path.exists("pylintrc"): return os.path.abspath("pylintrc") if os.path.exists(".pylintrc"): return os.path.abspath(".pylintrc") if os.path.isfile("__init__.py"): curdir = os.path.abspath(os.getcwd()) while os.path.isfile(os.path.join(curdir, "__init__.py")): curdir = os.path.abspath(os.path.join(curdir, "..")) if os.path.isfile(os.path.join(curdir, "pylintrc")): return os.path.join(curdir, "pylintrc") if os.path.isfile(os.path.join(curdir, ".pylintrc")): return os.path.join(curdir, ".pylintrc") if "PYLINTRC" in os.environ and os.path.exists(os.environ["PYLINTRC"]): pylintrc = os.environ["PYLINTRC"] else: user_home = os.path.expanduser("~") if user_home in ("~", "/root"): pylintrc = ".pylintrc" else: pylintrc = os.path.join(user_home, ".pylintrc") if not os.path.isfile(pylintrc): pylintrc = os.path.join(user_home, ".config", "pylintrc") if not os.path.isfile(pylintrc): if os.path.isfile("/etc/pylintrc"): pylintrc = "/etc/pylintrc" else: pylintrc = None return pylintrc
def find_pylintrc(): """search the pylint rc file and return its path if it find it, else None """ # is there a pylint rc file in the current directory ? if os.path.exists("pylintrc"): return os.path.abspath("pylintrc") if os.path.exists(".pylintrc"): return os.path.abspath(".pylintrc") if os.path.isfile("__init__.py"): curdir = os.path.abspath(os.getcwd()) while os.path.isfile(os.path.join(curdir, "__init__.py")): curdir = os.path.abspath(os.path.join(curdir, "..")) if os.path.isfile(os.path.join(curdir, "pylintrc")): return os.path.join(curdir, "pylintrc") if os.path.isfile(os.path.join(curdir, ".pylintrc")): return os.path.join(curdir, ".pylintrc") if "PYLINTRC" in os.environ and os.path.exists(os.environ["PYLINTRC"]): pylintrc = os.environ["PYLINTRC"] else: user_home = os.path.expanduser("~") if user_home in ("~", "/root"): pylintrc = ".pylintrc" else: pylintrc = os.path.join(user_home, ".pylintrc") if not os.path.isfile(pylintrc): pylintrc = os.path.join(user_home, ".config", "pylintrc") if not os.path.isfile(pylintrc): if os.path.isfile("/etc/pylintrc"): pylintrc = "/etc/pylintrc" else: pylintrc = None return pylintrc
[ "search", "the", "pylint", "rc", "file", "and", "return", "its", "path", "if", "it", "find", "it", "else", "None" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L105-L136
[ "def", "find_pylintrc", "(", ")", ":", "# is there a pylint rc file in the current directory ?", "if", "os", ".", "path", ".", "exists", "(", "\"pylintrc\"", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "\"pylintrc\"", ")", "if", "os", ".", "path", ".", "exists", "(", "\".pylintrc\"", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "\".pylintrc\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "\"__init__.py\"", ")", ":", "curdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "getcwd", "(", ")", ")", "while", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "curdir", ",", "\"__init__.py\"", ")", ")", ":", "curdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "curdir", ",", "\"..\"", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "curdir", ",", "\"pylintrc\"", ")", ")", ":", "return", "os", ".", "path", ".", "join", "(", "curdir", ",", "\"pylintrc\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "curdir", ",", "\".pylintrc\"", ")", ")", ":", "return", "os", ".", "path", ".", "join", "(", "curdir", ",", "\".pylintrc\"", ")", "if", "\"PYLINTRC\"", "in", "os", ".", "environ", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "environ", "[", "\"PYLINTRC\"", "]", ")", ":", "pylintrc", "=", "os", ".", "environ", "[", "\"PYLINTRC\"", "]", "else", ":", "user_home", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "if", "user_home", "in", "(", "\"~\"", ",", "\"/root\"", ")", ":", "pylintrc", "=", "\".pylintrc\"", "else", ":", "pylintrc", "=", "os", ".", "path", ".", "join", "(", "user_home", ",", "\".pylintrc\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "pylintrc", ")", ":", "pylintrc", "=", "os", ".", "path", ".", "join", "(", "user_home", ",", "\".config\"", ",", "\"pylintrc\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "pylintrc", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "\"/etc/pylintrc\"", ")", ":", "pylintrc", "=", "\"/etc/pylintrc\"", "else", ":", "pylintrc", "=", "None", "return", "pylintrc" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_validate
return a validated value for an option according to its type optional argument name is only used for error message formatting
pylint/config.py
def _validate(value, optdict, name=""): """return a validated value for an option according to its type optional argument name is only used for error message formatting """ try: _type = optdict["type"] except KeyError: # FIXME return value return _call_validator(_type, optdict, name, value)
def _validate(value, optdict, name=""): """return a validated value for an option according to its type optional argument name is only used for error message formatting """ try: _type = optdict["type"] except KeyError: # FIXME return value return _call_validator(_type, optdict, name, value)
[ "return", "a", "validated", "value", "for", "an", "option", "according", "to", "its", "type" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L240-L250
[ "def", "_validate", "(", "value", ",", "optdict", ",", "name", "=", "\"\"", ")", ":", "try", ":", "_type", "=", "optdict", "[", "\"type\"", "]", "except", "KeyError", ":", "# FIXME", "return", "value", "return", "_call_validator", "(", "_type", ",", "optdict", ",", "name", ",", "value", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_expand_default
Patch OptionParser.expand_default with custom behaviour This will handle defaults to avoid overriding values in the configuration file.
pylint/config.py
def _expand_default(self, option): """Patch OptionParser.expand_default with custom behaviour This will handle defaults to avoid overriding values in the configuration file. """ if self.parser is None or not self.default_tag: return option.help optname = option._long_opts[0][2:] try: provider = self.parser.options_manager._all_options[optname] except KeyError: value = None else: optdict = provider.get_option_def(optname) optname = provider.option_attrname(optname, optdict) value = getattr(provider.config, optname, optdict) value = utils._format_option_value(optdict, value) if value is optparse.NO_DEFAULT or not value: value = self.NO_DEFAULT_VALUE return option.help.replace(self.default_tag, str(value))
def _expand_default(self, option): """Patch OptionParser.expand_default with custom behaviour This will handle defaults to avoid overriding values in the configuration file. """ if self.parser is None or not self.default_tag: return option.help optname = option._long_opts[0][2:] try: provider = self.parser.options_manager._all_options[optname] except KeyError: value = None else: optdict = provider.get_option_def(optname) optname = provider.option_attrname(optname, optdict) value = getattr(provider.config, optname, optdict) value = utils._format_option_value(optdict, value) if value is optparse.NO_DEFAULT or not value: value = self.NO_DEFAULT_VALUE return option.help.replace(self.default_tag, str(value))
[ "Patch", "OptionParser", ".", "expand_default", "with", "custom", "behaviour" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L262-L282
[ "def", "_expand_default", "(", "self", ",", "option", ")", ":", "if", "self", ".", "parser", "is", "None", "or", "not", "self", ".", "default_tag", ":", "return", "option", ".", "help", "optname", "=", "option", ".", "_long_opts", "[", "0", "]", "[", "2", ":", "]", "try", ":", "provider", "=", "self", ".", "parser", ".", "options_manager", ".", "_all_options", "[", "optname", "]", "except", "KeyError", ":", "value", "=", "None", "else", ":", "optdict", "=", "provider", ".", "get_option_def", "(", "optname", ")", "optname", "=", "provider", ".", "option_attrname", "(", "optname", ",", "optdict", ")", "value", "=", "getattr", "(", "provider", ".", "config", ",", "optname", ",", "optdict", ")", "value", "=", "utils", ".", "_format_option_value", "(", "optdict", ",", "value", ")", "if", "value", "is", "optparse", ".", "NO_DEFAULT", "or", "not", "value", ":", "value", "=", "self", ".", "NO_DEFAULT_VALUE", "return", "option", ".", "help", ".", "replace", "(", "self", ".", "default_tag", ",", "str", "(", "value", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionParser._match_long_opt
Disable abbreviations.
pylint/config.py
def _match_long_opt(self, opt): """Disable abbreviations.""" if opt not in self._long_opt: raise optparse.BadOptionError(opt) return opt
def _match_long_opt(self, opt): """Disable abbreviations.""" if opt not in self._long_opt: raise optparse.BadOptionError(opt) return opt
[ "Disable", "abbreviations", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L383-L387
[ "def", "_match_long_opt", "(", "self", ",", "opt", ")", ":", "if", "opt", "not", "in", "self", ".", "_long_opt", ":", "raise", "optparse", ".", "BadOptionError", "(", "opt", ")", "return", "opt" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.register_options_provider
register an options provider
pylint/config.py
def register_options_provider(self, provider, own_group=True): """register an options provider""" assert provider.priority <= 0, "provider's priority can't be >= 0" for i in range(len(self.options_providers)): if provider.priority > self.options_providers[i].priority: self.options_providers.insert(i, provider) break else: self.options_providers.append(provider) non_group_spec_options = [ option for option in provider.options if "group" not in option[1] ] groups = getattr(provider, "option_groups", ()) if own_group and non_group_spec_options: self.add_option_group( provider.name.upper(), provider.__doc__, non_group_spec_options, provider, ) else: for opt, optdict in non_group_spec_options: self.add_optik_option(provider, self.cmdline_parser, opt, optdict) for gname, gdoc in groups: gname = gname.upper() goptions = [ option for option in provider.options if option[1].get("group", "").upper() == gname ] self.add_option_group(gname, gdoc, goptions, provider)
def register_options_provider(self, provider, own_group=True): """register an options provider""" assert provider.priority <= 0, "provider's priority can't be >= 0" for i in range(len(self.options_providers)): if provider.priority > self.options_providers[i].priority: self.options_providers.insert(i, provider) break else: self.options_providers.append(provider) non_group_spec_options = [ option for option in provider.options if "group" not in option[1] ] groups = getattr(provider, "option_groups", ()) if own_group and non_group_spec_options: self.add_option_group( provider.name.upper(), provider.__doc__, non_group_spec_options, provider, ) else: for opt, optdict in non_group_spec_options: self.add_optik_option(provider, self.cmdline_parser, opt, optdict) for gname, gdoc in groups: gname = gname.upper() goptions = [ option for option in provider.options if option[1].get("group", "").upper() == gname ] self.add_option_group(gname, gdoc, goptions, provider)
[ "register", "an", "options", "provider" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L540-L570
[ "def", "register_options_provider", "(", "self", ",", "provider", ",", "own_group", "=", "True", ")", ":", "assert", "provider", ".", "priority", "<=", "0", ",", "\"provider's priority can't be >= 0\"", "for", "i", "in", "range", "(", "len", "(", "self", ".", "options_providers", ")", ")", ":", "if", "provider", ".", "priority", ">", "self", ".", "options_providers", "[", "i", "]", ".", "priority", ":", "self", ".", "options_providers", ".", "insert", "(", "i", ",", "provider", ")", "break", "else", ":", "self", ".", "options_providers", ".", "append", "(", "provider", ")", "non_group_spec_options", "=", "[", "option", "for", "option", "in", "provider", ".", "options", "if", "\"group\"", "not", "in", "option", "[", "1", "]", "]", "groups", "=", "getattr", "(", "provider", ",", "\"option_groups\"", ",", "(", ")", ")", "if", "own_group", "and", "non_group_spec_options", ":", "self", ".", "add_option_group", "(", "provider", ".", "name", ".", "upper", "(", ")", ",", "provider", ".", "__doc__", ",", "non_group_spec_options", ",", "provider", ",", ")", "else", ":", "for", "opt", ",", "optdict", "in", "non_group_spec_options", ":", "self", ".", "add_optik_option", "(", "provider", ",", "self", ".", "cmdline_parser", ",", "opt", ",", "optdict", ")", "for", "gname", ",", "gdoc", "in", "groups", ":", "gname", "=", "gname", ".", "upper", "(", ")", "goptions", "=", "[", "option", "for", "option", "in", "provider", ".", "options", "if", "option", "[", "1", "]", ".", "get", "(", "\"group\"", ",", "\"\"", ")", ".", "upper", "(", ")", "==", "gname", "]", "self", ".", "add_option_group", "(", "gname", ",", "gdoc", ",", "goptions", ",", "provider", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.optik_option
get our personal option definition and return a suitable form for use with optik/optparse
pylint/config.py
def optik_option(self, provider, opt, optdict): """get our personal option definition and return a suitable form for use with optik/optparse """ optdict = copy.copy(optdict) if "action" in optdict: self._nocallback_options[provider] = opt else: optdict["action"] = "callback" optdict["callback"] = self.cb_set_provider_option # default is handled here and *must not* be given to optik if you # want the whole machinery to work if "default" in optdict: if ( "help" in optdict and optdict.get("default") is not None and optdict["action"] not in ("store_true", "store_false") ): optdict["help"] += " [current: %default]" del optdict["default"] args = ["--" + str(opt)] if "short" in optdict: self._short_options[optdict["short"]] = opt args.append("-" + optdict["short"]) del optdict["short"] # cleanup option definition dict before giving it to optik for key in list(optdict.keys()): if key not in self._optik_option_attrs: optdict.pop(key) return args, optdict
def optik_option(self, provider, opt, optdict): """get our personal option definition and return a suitable form for use with optik/optparse """ optdict = copy.copy(optdict) if "action" in optdict: self._nocallback_options[provider] = opt else: optdict["action"] = "callback" optdict["callback"] = self.cb_set_provider_option # default is handled here and *must not* be given to optik if you # want the whole machinery to work if "default" in optdict: if ( "help" in optdict and optdict.get("default") is not None and optdict["action"] not in ("store_true", "store_false") ): optdict["help"] += " [current: %default]" del optdict["default"] args = ["--" + str(opt)] if "short" in optdict: self._short_options[optdict["short"]] = opt args.append("-" + optdict["short"]) del optdict["short"] # cleanup option definition dict before giving it to optik for key in list(optdict.keys()): if key not in self._optik_option_attrs: optdict.pop(key) return args, optdict
[ "get", "our", "personal", "option", "definition", "and", "return", "a", "suitable", "form", "for", "use", "with", "optik", "/", "optparse" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L599-L628
[ "def", "optik_option", "(", "self", ",", "provider", ",", "opt", ",", "optdict", ")", ":", "optdict", "=", "copy", ".", "copy", "(", "optdict", ")", "if", "\"action\"", "in", "optdict", ":", "self", ".", "_nocallback_options", "[", "provider", "]", "=", "opt", "else", ":", "optdict", "[", "\"action\"", "]", "=", "\"callback\"", "optdict", "[", "\"callback\"", "]", "=", "self", ".", "cb_set_provider_option", "# default is handled here and *must not* be given to optik if you", "# want the whole machinery to work", "if", "\"default\"", "in", "optdict", ":", "if", "(", "\"help\"", "in", "optdict", "and", "optdict", ".", "get", "(", "\"default\"", ")", "is", "not", "None", "and", "optdict", "[", "\"action\"", "]", "not", "in", "(", "\"store_true\"", ",", "\"store_false\"", ")", ")", ":", "optdict", "[", "\"help\"", "]", "+=", "\" [current: %default]\"", "del", "optdict", "[", "\"default\"", "]", "args", "=", "[", "\"--\"", "+", "str", "(", "opt", ")", "]", "if", "\"short\"", "in", "optdict", ":", "self", ".", "_short_options", "[", "optdict", "[", "\"short\"", "]", "]", "=", "opt", "args", ".", "append", "(", "\"-\"", "+", "optdict", "[", "\"short\"", "]", ")", "del", "optdict", "[", "\"short\"", "]", "# cleanup option definition dict before giving it to optik", "for", "key", "in", "list", "(", "optdict", ".", "keys", "(", ")", ")", ":", "if", "key", "not", "in", "self", ".", "_optik_option_attrs", ":", "optdict", ".", "pop", "(", "key", ")", "return", "args", ",", "optdict" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.cb_set_provider_option
optik callback for option setting
pylint/config.py
def cb_set_provider_option(self, option, opt, value, parser): """optik callback for option setting""" if opt.startswith("--"): # remove -- on long option opt = opt[2:] else: # short option, get its long equivalent opt = self._short_options[opt[1:]] # trick since we can't set action='store_true' on options if value is None: value = 1 self.global_set_option(opt, value)
def cb_set_provider_option(self, option, opt, value, parser): """optik callback for option setting""" if opt.startswith("--"): # remove -- on long option opt = opt[2:] else: # short option, get its long equivalent opt = self._short_options[opt[1:]] # trick since we can't set action='store_true' on options if value is None: value = 1 self.global_set_option(opt, value)
[ "optik", "callback", "for", "option", "setting" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L630-L641
[ "def", "cb_set_provider_option", "(", "self", ",", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "if", "opt", ".", "startswith", "(", "\"--\"", ")", ":", "# remove -- on long option", "opt", "=", "opt", "[", "2", ":", "]", "else", ":", "# short option, get its long equivalent", "opt", "=", "self", ".", "_short_options", "[", "opt", "[", "1", ":", "]", "]", "# trick since we can't set action='store_true' on options", "if", "value", "is", "None", ":", "value", "=", "1", "self", ".", "global_set_option", "(", "opt", ",", "value", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.global_set_option
set option on the correct option provider
pylint/config.py
def global_set_option(self, opt, value): """set option on the correct option provider""" self._all_options[opt].set_option(opt, value)
def global_set_option(self, opt, value): """set option on the correct option provider""" self._all_options[opt].set_option(opt, value)
[ "set", "option", "on", "the", "correct", "option", "provider" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L643-L645
[ "def", "global_set_option", "(", "self", ",", "opt", ",", "value", ")", ":", "self", ".", "_all_options", "[", "opt", "]", ".", "set_option", "(", "opt", ",", "value", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.generate_config
write a configuration file according to the current configuration into the given stream or stdout
pylint/config.py
def generate_config(self, stream=None, skipsections=(), encoding=None): """write a configuration file according to the current configuration into the given stream or stdout """ options_by_section = {} sections = [] for provider in self.options_providers: for section, options in provider.options_by_section(): if section is None: section = provider.name if section in skipsections: continue options = [ (n, d, v) for (n, d, v) in options if d.get("type") is not None and not d.get("deprecated") ] if not options: continue if section not in sections: sections.append(section) alloptions = options_by_section.setdefault(section, []) alloptions += options stream = stream or sys.stdout printed = False for section in sections: if printed: print("\n", file=stream) utils.format_section( stream, section.upper(), sorted(options_by_section[section]) ) printed = True
def generate_config(self, stream=None, skipsections=(), encoding=None): """write a configuration file according to the current configuration into the given stream or stdout """ options_by_section = {} sections = [] for provider in self.options_providers: for section, options in provider.options_by_section(): if section is None: section = provider.name if section in skipsections: continue options = [ (n, d, v) for (n, d, v) in options if d.get("type") is not None and not d.get("deprecated") ] if not options: continue if section not in sections: sections.append(section) alloptions = options_by_section.setdefault(section, []) alloptions += options stream = stream or sys.stdout printed = False for section in sections: if printed: print("\n", file=stream) utils.format_section( stream, section.upper(), sorted(options_by_section[section]) ) printed = True
[ "write", "a", "configuration", "file", "according", "to", "the", "current", "configuration", "into", "the", "given", "stream", "or", "stdout" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L647-L678
[ "def", "generate_config", "(", "self", ",", "stream", "=", "None", ",", "skipsections", "=", "(", ")", ",", "encoding", "=", "None", ")", ":", "options_by_section", "=", "{", "}", "sections", "=", "[", "]", "for", "provider", "in", "self", ".", "options_providers", ":", "for", "section", ",", "options", "in", "provider", ".", "options_by_section", "(", ")", ":", "if", "section", "is", "None", ":", "section", "=", "provider", ".", "name", "if", "section", "in", "skipsections", ":", "continue", "options", "=", "[", "(", "n", ",", "d", ",", "v", ")", "for", "(", "n", ",", "d", ",", "v", ")", "in", "options", "if", "d", ".", "get", "(", "\"type\"", ")", "is", "not", "None", "and", "not", "d", ".", "get", "(", "\"deprecated\"", ")", "]", "if", "not", "options", ":", "continue", "if", "section", "not", "in", "sections", ":", "sections", ".", "append", "(", "section", ")", "alloptions", "=", "options_by_section", ".", "setdefault", "(", "section", ",", "[", "]", ")", "alloptions", "+=", "options", "stream", "=", "stream", "or", "sys", ".", "stdout", "printed", "=", "False", "for", "section", "in", "sections", ":", "if", "printed", ":", "print", "(", "\"\\n\"", ",", "file", "=", "stream", ")", "utils", ".", "format_section", "(", "stream", ",", "section", ".", "upper", "(", ")", ",", "sorted", "(", "options_by_section", "[", "section", "]", ")", ")", "printed", "=", "True" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.read_config_file
read the configuration file but do not load it (i.e. dispatching values to each options provider)
pylint/config.py
def read_config_file(self, config_file=None, verbose=None): """read the configuration file but do not load it (i.e. dispatching values to each options provider) """ helplevel = 1 while helplevel <= self._maxlevel: opt = "-".join(["long"] * helplevel) + "-help" if opt in self._all_options: break # already processed # pylint: disable=unused-argument def helpfunc(option, opt, val, p, level=helplevel): print(self.help(level)) sys.exit(0) helpmsg = "%s verbose help." % " ".join(["more"] * helplevel) optdict = {"action": "callback", "callback": helpfunc, "help": helpmsg} provider = self.options_providers[0] self.add_optik_option(provider, self.cmdline_parser, opt, optdict) provider.options += ((opt, optdict),) helplevel += 1 if config_file is None: config_file = self.config_file if config_file is not None: config_file = os.path.expanduser(config_file) if not os.path.exists(config_file): raise IOError("The config file {:s} doesn't exist!".format(config_file)) use_config_file = config_file and os.path.exists(config_file) if use_config_file: parser = self.cfgfile_parser # Use this encoding in order to strip the BOM marker, if any. with io.open(config_file, "r", encoding="utf_8_sig") as fp: parser.read_file(fp) # normalize sections'title for sect, values in list(parser._sections.items()): if not sect.isupper() and values: parser._sections[sect.upper()] = values if not verbose: return if use_config_file: msg = "Using config file {}".format(os.path.abspath(config_file)) else: msg = "No config file found, using default configuration" print(msg, file=sys.stderr)
def read_config_file(self, config_file=None, verbose=None): """read the configuration file but do not load it (i.e. dispatching values to each options provider) """ helplevel = 1 while helplevel <= self._maxlevel: opt = "-".join(["long"] * helplevel) + "-help" if opt in self._all_options: break # already processed # pylint: disable=unused-argument def helpfunc(option, opt, val, p, level=helplevel): print(self.help(level)) sys.exit(0) helpmsg = "%s verbose help." % " ".join(["more"] * helplevel) optdict = {"action": "callback", "callback": helpfunc, "help": helpmsg} provider = self.options_providers[0] self.add_optik_option(provider, self.cmdline_parser, opt, optdict) provider.options += ((opt, optdict),) helplevel += 1 if config_file is None: config_file = self.config_file if config_file is not None: config_file = os.path.expanduser(config_file) if not os.path.exists(config_file): raise IOError("The config file {:s} doesn't exist!".format(config_file)) use_config_file = config_file and os.path.exists(config_file) if use_config_file: parser = self.cfgfile_parser # Use this encoding in order to strip the BOM marker, if any. with io.open(config_file, "r", encoding="utf_8_sig") as fp: parser.read_file(fp) # normalize sections'title for sect, values in list(parser._sections.items()): if not sect.isupper() and values: parser._sections[sect.upper()] = values if not verbose: return if use_config_file: msg = "Using config file {}".format(os.path.abspath(config_file)) else: msg = "No config file found, using default configuration" print(msg, file=sys.stderr)
[ "read", "the", "configuration", "file", "but", "do", "not", "load", "it", "(", "i", ".", "e", ".", "dispatching", "values", "to", "each", "options", "provider", ")" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L695-L742
[ "def", "read_config_file", "(", "self", ",", "config_file", "=", "None", ",", "verbose", "=", "None", ")", ":", "helplevel", "=", "1", "while", "helplevel", "<=", "self", ".", "_maxlevel", ":", "opt", "=", "\"-\"", ".", "join", "(", "[", "\"long\"", "]", "*", "helplevel", ")", "+", "\"-help\"", "if", "opt", "in", "self", ".", "_all_options", ":", "break", "# already processed", "# pylint: disable=unused-argument", "def", "helpfunc", "(", "option", ",", "opt", ",", "val", ",", "p", ",", "level", "=", "helplevel", ")", ":", "print", "(", "self", ".", "help", "(", "level", ")", ")", "sys", ".", "exit", "(", "0", ")", "helpmsg", "=", "\"%s verbose help.\"", "%", "\" \"", ".", "join", "(", "[", "\"more\"", "]", "*", "helplevel", ")", "optdict", "=", "{", "\"action\"", ":", "\"callback\"", ",", "\"callback\"", ":", "helpfunc", ",", "\"help\"", ":", "helpmsg", "}", "provider", "=", "self", ".", "options_providers", "[", "0", "]", "self", ".", "add_optik_option", "(", "provider", ",", "self", ".", "cmdline_parser", ",", "opt", ",", "optdict", ")", "provider", ".", "options", "+=", "(", "(", "opt", ",", "optdict", ")", ",", ")", "helplevel", "+=", "1", "if", "config_file", "is", "None", ":", "config_file", "=", "self", ".", "config_file", "if", "config_file", "is", "not", "None", ":", "config_file", "=", "os", ".", "path", ".", "expanduser", "(", "config_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "raise", "IOError", "(", "\"The config file {:s} doesn't exist!\"", ".", "format", "(", "config_file", ")", ")", "use_config_file", "=", "config_file", "and", "os", ".", "path", ".", "exists", "(", "config_file", ")", "if", "use_config_file", ":", "parser", "=", "self", ".", "cfgfile_parser", "# Use this encoding in order to strip the BOM marker, if any.", "with", "io", ".", "open", "(", "config_file", ",", "\"r\"", ",", "encoding", "=", "\"utf_8_sig\"", ")", "as", "fp", ":", "parser", ".", "read_file", "(", "fp", ")", "# normalize sections'title", "for", "sect", ",", "values", "in", "list", "(", "parser", ".", "_sections", ".", "items", "(", ")", ")", ":", "if", "not", "sect", ".", "isupper", "(", ")", "and", "values", ":", "parser", ".", "_sections", "[", "sect", ".", "upper", "(", ")", "]", "=", "values", "if", "not", "verbose", ":", "return", "if", "use_config_file", ":", "msg", "=", "\"Using config file {}\"", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config_file", ")", ")", "else", ":", "msg", "=", "\"No config file found, using default configuration\"", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.load_config_file
dispatch values previously read from a configuration file to each options provider)
pylint/config.py
def load_config_file(self): """dispatch values previously read from a configuration file to each options provider) """ parser = self.cfgfile_parser for section in parser.sections(): for option, value in parser.items(section): try: self.global_set_option(option, value) except (KeyError, optparse.OptionError): # TODO handle here undeclared options appearing in the config file continue
def load_config_file(self): """dispatch values previously read from a configuration file to each options provider) """ parser = self.cfgfile_parser for section in parser.sections(): for option, value in parser.items(section): try: self.global_set_option(option, value) except (KeyError, optparse.OptionError): # TODO handle here undeclared options appearing in the config file continue
[ "dispatch", "values", "previously", "read", "from", "a", "configuration", "file", "to", "each", "options", "provider", ")" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L744-L755
[ "def", "load_config_file", "(", "self", ")", ":", "parser", "=", "self", ".", "cfgfile_parser", "for", "section", "in", "parser", ".", "sections", "(", ")", ":", "for", "option", ",", "value", "in", "parser", ".", "items", "(", "section", ")", ":", "try", ":", "self", ".", "global_set_option", "(", "option", ",", "value", ")", "except", "(", "KeyError", ",", "optparse", ".", "OptionError", ")", ":", "# TODO handle here undeclared options appearing in the config file", "continue" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.load_command_line_configuration
Override configuration according to command line parameters return additional arguments
pylint/config.py
def load_command_line_configuration(self, args=None): """Override configuration according to command line parameters return additional arguments """ with _patch_optparse(): if args is None: args = sys.argv[1:] else: args = list(args) (options, args) = self.cmdline_parser.parse_args(args=args) for provider in self._nocallback_options: config = provider.config for attr in config.__dict__.keys(): value = getattr(options, attr, None) if value is None: continue setattr(config, attr, value) return args
def load_command_line_configuration(self, args=None): """Override configuration according to command line parameters return additional arguments """ with _patch_optparse(): if args is None: args = sys.argv[1:] else: args = list(args) (options, args) = self.cmdline_parser.parse_args(args=args) for provider in self._nocallback_options: config = provider.config for attr in config.__dict__.keys(): value = getattr(options, attr, None) if value is None: continue setattr(config, attr, value) return args
[ "Override", "configuration", "according", "to", "command", "line", "parameters" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L767-L785
[ "def", "load_command_line_configuration", "(", "self", ",", "args", "=", "None", ")", ":", "with", "_patch_optparse", "(", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "args", "=", "list", "(", "args", ")", "(", "options", ",", "args", ")", "=", "self", ".", "cmdline_parser", ".", "parse_args", "(", "args", "=", "args", ")", "for", "provider", "in", "self", ".", "_nocallback_options", ":", "config", "=", "provider", ".", "config", "for", "attr", "in", "config", ".", "__dict__", ".", "keys", "(", ")", ":", "value", "=", "getattr", "(", "options", ",", "attr", ",", "None", ")", "if", "value", "is", "None", ":", "continue", "setattr", "(", "config", ",", "attr", ",", "value", ")", "return", "args" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.add_help_section
add a dummy option section for help purpose
pylint/config.py
def add_help_section(self, title, description, level=0): """add a dummy option section for help purpose """ group = optparse.OptionGroup( self.cmdline_parser, title=title.capitalize(), description=description ) group.level = level self._maxlevel = max(self._maxlevel, level) self.cmdline_parser.add_option_group(group)
def add_help_section(self, title, description, level=0): """add a dummy option section for help purpose """ group = optparse.OptionGroup( self.cmdline_parser, title=title.capitalize(), description=description ) group.level = level self._maxlevel = max(self._maxlevel, level) self.cmdline_parser.add_option_group(group)
[ "add", "a", "dummy", "option", "section", "for", "help", "purpose" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L787-L794
[ "def", "add_help_section", "(", "self", ",", "title", ",", "description", ",", "level", "=", "0", ")", ":", "group", "=", "optparse", ".", "OptionGroup", "(", "self", ".", "cmdline_parser", ",", "title", "=", "title", ".", "capitalize", "(", ")", ",", "description", "=", "description", ")", "group", ".", "level", "=", "level", "self", ".", "_maxlevel", "=", "max", "(", "self", ".", "_maxlevel", ",", "level", ")", "self", ".", "cmdline_parser", ".", "add_option_group", "(", "group", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsManagerMixIn.help
return the usage string for available options
pylint/config.py
def help(self, level=0): """return the usage string for available options """ self.cmdline_parser.formatter.output_level = level with _patch_optparse(): return self.cmdline_parser.format_help()
def help(self, level=0): """return the usage string for available options """ self.cmdline_parser.formatter.output_level = level with _patch_optparse(): return self.cmdline_parser.format_help()
[ "return", "the", "usage", "string", "for", "available", "options" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L796-L800
[ "def", "help", "(", "self", ",", "level", "=", "0", ")", ":", "self", ".", "cmdline_parser", ".", "formatter", ".", "output_level", "=", "level", "with", "_patch_optparse", "(", ")", ":", "return", "self", ".", "cmdline_parser", ".", "format_help", "(", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsProviderMixIn.load_defaults
initialize the provider using default values
pylint/config.py
def load_defaults(self): """initialize the provider using default values""" for opt, optdict in self.options: action = optdict.get("action") if action != "callback": # callback action have no default if optdict is None: optdict = self.get_option_def(opt) default = optdict.get("default") self.set_option(opt, default, action, optdict)
def load_defaults(self): """initialize the provider using default values""" for opt, optdict in self.options: action = optdict.get("action") if action != "callback": # callback action have no default if optdict is None: optdict = self.get_option_def(opt) default = optdict.get("default") self.set_option(opt, default, action, optdict)
[ "initialize", "the", "provider", "using", "default", "values" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L816-L825
[ "def", "load_defaults", "(", "self", ")", ":", "for", "opt", ",", "optdict", "in", "self", ".", "options", ":", "action", "=", "optdict", ".", "get", "(", "\"action\"", ")", "if", "action", "!=", "\"callback\"", ":", "# callback action have no default", "if", "optdict", "is", "None", ":", "optdict", "=", "self", ".", "get_option_def", "(", "opt", ")", "default", "=", "optdict", ".", "get", "(", "\"default\"", ")", "self", ".", "set_option", "(", "opt", ",", "default", ",", "action", ",", "optdict", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsProviderMixIn.option_attrname
get the config attribute corresponding to opt
pylint/config.py
def option_attrname(self, opt, optdict=None): """get the config attribute corresponding to opt""" if optdict is None: optdict = self.get_option_def(opt) return optdict.get("dest", opt.replace("-", "_"))
def option_attrname(self, opt, optdict=None): """get the config attribute corresponding to opt""" if optdict is None: optdict = self.get_option_def(opt) return optdict.get("dest", opt.replace("-", "_"))
[ "get", "the", "config", "attribute", "corresponding", "to", "opt" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L827-L831
[ "def", "option_attrname", "(", "self", ",", "opt", ",", "optdict", "=", "None", ")", ":", "if", "optdict", "is", "None", ":", "optdict", "=", "self", ".", "get_option_def", "(", "opt", ")", "return", "optdict", ".", "get", "(", "\"dest\"", ",", "opt", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsProviderMixIn.set_option
method called to set an option (registered in the options list)
pylint/config.py
def set_option(self, optname, value, action=None, optdict=None): """method called to set an option (registered in the options list)""" if optdict is None: optdict = self.get_option_def(optname) if value is not None: value = _validate(value, optdict, optname) if action is None: action = optdict.get("action", "store") if action == "store": setattr(self.config, self.option_attrname(optname, optdict), value) elif action in ("store_true", "count"): setattr(self.config, self.option_attrname(optname, optdict), 0) elif action == "store_false": setattr(self.config, self.option_attrname(optname, optdict), 1) elif action == "append": optname = self.option_attrname(optname, optdict) _list = getattr(self.config, optname, None) if _list is None: if isinstance(value, (list, tuple)): _list = value elif value is not None: _list = [] _list.append(value) setattr(self.config, optname, _list) elif isinstance(_list, tuple): setattr(self.config, optname, _list + (value,)) else: _list.append(value) elif action == "callback": optdict["callback"](None, optname, value, None) else: raise UnsupportedAction(action)
def set_option(self, optname, value, action=None, optdict=None): """method called to set an option (registered in the options list)""" if optdict is None: optdict = self.get_option_def(optname) if value is not None: value = _validate(value, optdict, optname) if action is None: action = optdict.get("action", "store") if action == "store": setattr(self.config, self.option_attrname(optname, optdict), value) elif action in ("store_true", "count"): setattr(self.config, self.option_attrname(optname, optdict), 0) elif action == "store_false": setattr(self.config, self.option_attrname(optname, optdict), 1) elif action == "append": optname = self.option_attrname(optname, optdict) _list = getattr(self.config, optname, None) if _list is None: if isinstance(value, (list, tuple)): _list = value elif value is not None: _list = [] _list.append(value) setattr(self.config, optname, _list) elif isinstance(_list, tuple): setattr(self.config, optname, _list + (value,)) else: _list.append(value) elif action == "callback": optdict["callback"](None, optname, value, None) else: raise UnsupportedAction(action)
[ "method", "called", "to", "set", "an", "option", "(", "registered", "in", "the", "options", "list", ")" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L837-L868
[ "def", "set_option", "(", "self", ",", "optname", ",", "value", ",", "action", "=", "None", ",", "optdict", "=", "None", ")", ":", "if", "optdict", "is", "None", ":", "optdict", "=", "self", ".", "get_option_def", "(", "optname", ")", "if", "value", "is", "not", "None", ":", "value", "=", "_validate", "(", "value", ",", "optdict", ",", "optname", ")", "if", "action", "is", "None", ":", "action", "=", "optdict", ".", "get", "(", "\"action\"", ",", "\"store\"", ")", "if", "action", "==", "\"store\"", ":", "setattr", "(", "self", ".", "config", ",", "self", ".", "option_attrname", "(", "optname", ",", "optdict", ")", ",", "value", ")", "elif", "action", "in", "(", "\"store_true\"", ",", "\"count\"", ")", ":", "setattr", "(", "self", ".", "config", ",", "self", ".", "option_attrname", "(", "optname", ",", "optdict", ")", ",", "0", ")", "elif", "action", "==", "\"store_false\"", ":", "setattr", "(", "self", ".", "config", ",", "self", ".", "option_attrname", "(", "optname", ",", "optdict", ")", ",", "1", ")", "elif", "action", "==", "\"append\"", ":", "optname", "=", "self", ".", "option_attrname", "(", "optname", ",", "optdict", ")", "_list", "=", "getattr", "(", "self", ".", "config", ",", "optname", ",", "None", ")", "if", "_list", "is", "None", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "_list", "=", "value", "elif", "value", "is", "not", "None", ":", "_list", "=", "[", "]", "_list", ".", "append", "(", "value", ")", "setattr", "(", "self", ".", "config", ",", "optname", ",", "_list", ")", "elif", "isinstance", "(", "_list", ",", "tuple", ")", ":", "setattr", "(", "self", ".", "config", ",", "optname", ",", "_list", "+", "(", "value", ",", ")", ")", "else", ":", "_list", ".", "append", "(", "value", ")", "elif", "action", "==", "\"callback\"", ":", "optdict", "[", "\"callback\"", "]", "(", "None", ",", "optname", ",", "value", ",", "None", ")", "else", ":", "raise", "UnsupportedAction", "(", "action", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsProviderMixIn.get_option_def
return the dictionary defining an option given its name
pylint/config.py
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( "no such option %s in section %r" % (opt, self.name), opt )
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( "no such option %s in section %r" % (opt, self.name), opt )
[ "return", "the", "dictionary", "defining", "an", "option", "given", "its", "name" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L870-L878
[ "def", "get_option_def", "(", "self", ",", "opt", ")", ":", "assert", "self", ".", "options", "for", "option", "in", "self", ".", "options", ":", "if", "option", "[", "0", "]", "==", "opt", ":", "return", "option", "[", "1", "]", "raise", "optparse", ".", "OptionError", "(", "\"no such option %s in section %r\"", "%", "(", "opt", ",", "self", ".", "name", ")", ",", "opt", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
OptionsProviderMixIn.options_by_section
return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)])
pylint/config.py
def options_by_section(self): """return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)]) """ sections = {} for optname, optdict in self.options: sections.setdefault(optdict.get("group"), []).append( (optname, optdict, self.option_value(optname)) ) if None in sections: yield None, sections.pop(None) for section, options in sorted(sections.items()): yield section.upper(), options
def options_by_section(self): """return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)]) """ sections = {} for optname, optdict in self.options: sections.setdefault(optdict.get("group"), []).append( (optname, optdict, self.option_value(optname)) ) if None in sections: yield None, sections.pop(None) for section, options in sorted(sections.items()): yield section.upper(), options
[ "return", "an", "iterator", "on", "options", "grouped", "by", "section" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L880-L893
[ "def", "options_by_section", "(", "self", ")", ":", "sections", "=", "{", "}", "for", "optname", ",", "optdict", "in", "self", ".", "options", ":", "sections", ".", "setdefault", "(", "optdict", ".", "get", "(", "\"group\"", ")", ",", "[", "]", ")", ".", "append", "(", "(", "optname", ",", "optdict", ",", "self", ".", "option_value", "(", "optname", ")", ")", ")", "if", "None", "in", "sections", ":", "yield", "None", ",", "sections", ".", "pop", "(", "None", ")", "for", "section", ",", "options", "in", "sorted", "(", "sections", ".", "items", "(", ")", ")", ":", "yield", "section", ".", "upper", "(", ")", ",", "options" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
is_method_call
Determines if a BoundMethod node represents a method call. Args: func (astroid.BoundMethod): The BoundMethod AST node to check. types (Optional[String]): Optional sequence of caller type names to restrict check. methods (Optional[String]): Optional sequence of method names to restrict check. Returns: bool: true if the node represents a method call for the given type and method names, False otherwise.
pylint/checkers/logging.py
def is_method_call(func, types=(), methods=()): """Determines if a BoundMethod node represents a method call. Args: func (astroid.BoundMethod): The BoundMethod AST node to check. types (Optional[String]): Optional sequence of caller type names to restrict check. methods (Optional[String]): Optional sequence of method names to restrict check. Returns: bool: true if the node represents a method call for the given type and method names, False otherwise. """ return ( isinstance(func, astroid.BoundMethod) and isinstance(func.bound, astroid.Instance) and (func.bound.name in types if types else True) and (func.name in methods if methods else True) )
def is_method_call(func, types=(), methods=()): """Determines if a BoundMethod node represents a method call. Args: func (astroid.BoundMethod): The BoundMethod AST node to check. types (Optional[String]): Optional sequence of caller type names to restrict check. methods (Optional[String]): Optional sequence of method names to restrict check. Returns: bool: true if the node represents a method call for the given type and method names, False otherwise. """ return ( isinstance(func, astroid.BoundMethod) and isinstance(func.bound, astroid.Instance) and (func.bound.name in types if types else True) and (func.name in methods if methods else True) )
[ "Determines", "if", "a", "BoundMethod", "node", "represents", "a", "method", "call", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L99-L116
[ "def", "is_method_call", "(", "func", ",", "types", "=", "(", ")", ",", "methods", "=", "(", ")", ")", ":", "return", "(", "isinstance", "(", "func", ",", "astroid", ".", "BoundMethod", ")", "and", "isinstance", "(", "func", ".", "bound", ",", "astroid", ".", "Instance", ")", "and", "(", "func", ".", "bound", ".", "name", "in", "types", "if", "types", "else", "True", ")", "and", "(", "func", ".", "name", "in", "methods", "if", "methods", "else", "True", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
is_complex_format_str
Checks if node represents a string with complex formatting specs. Args: node (astroid.node_classes.NodeNG): AST node to check Returns: bool: True if inferred string uses complex formatting, False otherwise
pylint/checkers/logging.py
def is_complex_format_str(node): """Checks if node represents a string with complex formatting specs. Args: node (astroid.node_classes.NodeNG): AST node to check Returns: bool: True if inferred string uses complex formatting, False otherwise """ inferred = utils.safe_infer(node) if inferred is None or not isinstance(inferred.value, str): return True try: parsed = list(string.Formatter().parse(inferred.value)) except ValueError: # This format string is invalid return False for _, _, format_spec, _ in parsed: if format_spec: return True return False
def is_complex_format_str(node): """Checks if node represents a string with complex formatting specs. Args: node (astroid.node_classes.NodeNG): AST node to check Returns: bool: True if inferred string uses complex formatting, False otherwise """ inferred = utils.safe_infer(node) if inferred is None or not isinstance(inferred.value, str): return True try: parsed = list(string.Formatter().parse(inferred.value)) except ValueError: # This format string is invalid return False for _, _, format_spec, _ in parsed: if format_spec: return True return False
[ "Checks", "if", "node", "represents", "a", "string", "with", "complex", "formatting", "specs", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L333-L352
[ "def", "is_complex_format_str", "(", "node", ")", ":", "inferred", "=", "utils", ".", "safe_infer", "(", "node", ")", "if", "inferred", "is", "None", "or", "not", "isinstance", "(", "inferred", ".", "value", ",", "str", ")", ":", "return", "True", "try", ":", "parsed", "=", "list", "(", "string", ".", "Formatter", "(", ")", ".", "parse", "(", "inferred", ".", "value", ")", ")", "except", "ValueError", ":", "# This format string is invalid", "return", "False", "for", "_", ",", "_", ",", "format_spec", ",", "_", "in", "parsed", ":", "if", "format_spec", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker.visit_module
Clears any state left in this checker from last module checked.
pylint/checkers/logging.py
def visit_module(self, node): # pylint: disable=unused-argument """Clears any state left in this checker from last module checked.""" # The code being checked can just as easily "import logging as foo", # so it is necessary to process the imports and store in this field # what name the logging module is actually given. self._logging_names = set() logging_mods = self.config.logging_modules self._format_style = self.config.logging_format_style self._logging_modules = set(logging_mods) self._from_imports = {} for logging_mod in logging_mods: parts = logging_mod.rsplit(".", 1) if len(parts) > 1: self._from_imports[parts[0]] = parts[1]
def visit_module(self, node): # pylint: disable=unused-argument """Clears any state left in this checker from last module checked.""" # The code being checked can just as easily "import logging as foo", # so it is necessary to process the imports and store in this field # what name the logging module is actually given. self._logging_names = set() logging_mods = self.config.logging_modules self._format_style = self.config.logging_format_style self._logging_modules = set(logging_mods) self._from_imports = {} for logging_mod in logging_mods: parts = logging_mod.rsplit(".", 1) if len(parts) > 1: self._from_imports[parts[0]] = parts[1]
[ "Clears", "any", "state", "left", "in", "this", "checker", "from", "last", "module", "checked", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L150-L164
[ "def", "visit_module", "(", "self", ",", "node", ")", ":", "# pylint: disable=unused-argument", "# The code being checked can just as easily \"import logging as foo\",", "# so it is necessary to process the imports and store in this field", "# what name the logging module is actually given.", "self", ".", "_logging_names", "=", "set", "(", ")", "logging_mods", "=", "self", ".", "config", ".", "logging_modules", "self", ".", "_format_style", "=", "self", ".", "config", ".", "logging_format_style", "self", ".", "_logging_modules", "=", "set", "(", "logging_mods", ")", "self", ".", "_from_imports", "=", "{", "}", "for", "logging_mod", "in", "logging_mods", ":", "parts", "=", "logging_mod", ".", "rsplit", "(", "\".\"", ",", "1", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "self", ".", "_from_imports", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker.visit_importfrom
Checks to see if a module uses a non-Python logging module.
pylint/checkers/logging.py
def visit_importfrom(self, node): """Checks to see if a module uses a non-Python logging module.""" try: logging_name = self._from_imports[node.modname] for module, as_name in node.names: if module == logging_name: self._logging_names.add(as_name or module) except KeyError: pass
def visit_importfrom(self, node): """Checks to see if a module uses a non-Python logging module.""" try: logging_name = self._from_imports[node.modname] for module, as_name in node.names: if module == logging_name: self._logging_names.add(as_name or module) except KeyError: pass
[ "Checks", "to", "see", "if", "a", "module", "uses", "a", "non", "-", "Python", "logging", "module", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L166-L174
[ "def", "visit_importfrom", "(", "self", ",", "node", ")", ":", "try", ":", "logging_name", "=", "self", ".", "_from_imports", "[", "node", ".", "modname", "]", "for", "module", ",", "as_name", "in", "node", ".", "names", ":", "if", "module", "==", "logging_name", ":", "self", ".", "_logging_names", ".", "add", "(", "as_name", "or", "module", ")", "except", "KeyError", ":", "pass" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker.visit_import
Checks to see if this module uses Python's built-in logging.
pylint/checkers/logging.py
def visit_import(self, node): """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module)
def visit_import(self, node): """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module)
[ "Checks", "to", "see", "if", "this", "module", "uses", "Python", "s", "built", "-", "in", "logging", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L176-L180
[ "def", "visit_import", "(", "self", ",", "node", ")", ":", "for", "module", ",", "as_name", "in", "node", ".", "names", ":", "if", "module", "in", "self", ".", "_logging_modules", ":", "self", ".", "_logging_names", ".", "add", "(", "as_name", "or", "module", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker.visit_call
Checks calls to logging methods.
pylint/checkers/logging.py
def visit_call(self, node): """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): try: for inferred in node.func.infer(): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, astroid.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return True, inferred._proxied.name except astroid.exceptions.InferenceError: pass return False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name)
def visit_call(self, node): """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): try: for inferred in node.func.infer(): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, astroid.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return True, inferred._proxied.name except astroid.exceptions.InferenceError: pass return False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name)
[ "Checks", "calls", "to", "logging", "methods", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L183-L216
[ "def", "visit_call", "(", "self", ",", "node", ")", ":", "def", "is_logging_name", "(", ")", ":", "return", "(", "isinstance", "(", "node", ".", "func", ",", "astroid", ".", "Attribute", ")", "and", "isinstance", "(", "node", ".", "func", ".", "expr", ",", "astroid", ".", "Name", ")", "and", "node", ".", "func", ".", "expr", ".", "name", "in", "self", ".", "_logging_names", ")", "def", "is_logger_class", "(", ")", ":", "try", ":", "for", "inferred", "in", "node", ".", "func", ".", "infer", "(", ")", ":", "if", "isinstance", "(", "inferred", ",", "astroid", ".", "BoundMethod", ")", ":", "parent", "=", "inferred", ".", "_proxied", ".", "parent", "if", "isinstance", "(", "parent", ",", "astroid", ".", "ClassDef", ")", "and", "(", "parent", ".", "qname", "(", ")", "==", "\"logging.Logger\"", "or", "any", "(", "ancestor", ".", "qname", "(", ")", "==", "\"logging.Logger\"", "for", "ancestor", "in", "parent", ".", "ancestors", "(", ")", ")", ")", ":", "return", "True", ",", "inferred", ".", "_proxied", ".", "name", "except", "astroid", ".", "exceptions", ".", "InferenceError", ":", "pass", "return", "False", ",", "None", "if", "is_logging_name", "(", ")", ":", "name", "=", "node", ".", "func", ".", "attrname", "else", ":", "result", ",", "name", "=", "is_logger_class", "(", ")", "if", "not", "result", ":", "return", "self", ".", "_check_log_method", "(", "node", ",", "name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker._check_log_method
Checks calls to logging.log(level, format, *format_args).
pylint/checkers/logging.py
def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], astroid.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message("logging-not-lazy", node=node) elif isinstance(node.args[format_pos], astroid.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], astroid.Const): self._check_format_string(node, format_pos) elif isinstance( node.args[format_pos], (astroid.FormattedValue, astroid.JoinedStr) ): self.add_message("logging-fstring-interpolation", node=node)
def _check_log_method(self, node, name): """Checks calls to logging.log(level, format, *format_args).""" if name == "log": if node.starargs or node.kwargs or len(node.args) < 2: # Either a malformed call, star args, or double-star args. Beyond # the scope of this checker. return format_pos = 1 elif name in CHECKED_CONVENIENCE_FUNCTIONS: if node.starargs or node.kwargs or not node.args: # Either no args, star args, or double-star args. Beyond the # scope of this checker. return format_pos = 0 else: return if isinstance(node.args[format_pos], astroid.BinOp): binop = node.args[format_pos] emit = binop.op == "%" if binop.op == "+": total_number_of_strings = sum( 1 for operand in (binop.left, binop.right) if self._is_operand_literal_str(utils.safe_infer(operand)) ) emit = total_number_of_strings > 0 if emit: self.add_message("logging-not-lazy", node=node) elif isinstance(node.args[format_pos], astroid.Call): self._check_call_func(node.args[format_pos]) elif isinstance(node.args[format_pos], astroid.Const): self._check_format_string(node, format_pos) elif isinstance( node.args[format_pos], (astroid.FormattedValue, astroid.JoinedStr) ): self.add_message("logging-fstring-interpolation", node=node)
[ "Checks", "calls", "to", "logging", ".", "log", "(", "level", "format", "*", "format_args", ")", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L218-L254
[ "def", "_check_log_method", "(", "self", ",", "node", ",", "name", ")", ":", "if", "name", "==", "\"log\"", ":", "if", "node", ".", "starargs", "or", "node", ".", "kwargs", "or", "len", "(", "node", ".", "args", ")", "<", "2", ":", "# Either a malformed call, star args, or double-star args. Beyond", "# the scope of this checker.", "return", "format_pos", "=", "1", "elif", "name", "in", "CHECKED_CONVENIENCE_FUNCTIONS", ":", "if", "node", ".", "starargs", "or", "node", ".", "kwargs", "or", "not", "node", ".", "args", ":", "# Either no args, star args, or double-star args. Beyond the", "# scope of this checker.", "return", "format_pos", "=", "0", "else", ":", "return", "if", "isinstance", "(", "node", ".", "args", "[", "format_pos", "]", ",", "astroid", ".", "BinOp", ")", ":", "binop", "=", "node", ".", "args", "[", "format_pos", "]", "emit", "=", "binop", ".", "op", "==", "\"%\"", "if", "binop", ".", "op", "==", "\"+\"", ":", "total_number_of_strings", "=", "sum", "(", "1", "for", "operand", "in", "(", "binop", ".", "left", ",", "binop", ".", "right", ")", "if", "self", ".", "_is_operand_literal_str", "(", "utils", ".", "safe_infer", "(", "operand", ")", ")", ")", "emit", "=", "total_number_of_strings", ">", "0", "if", "emit", ":", "self", ".", "add_message", "(", "\"logging-not-lazy\"", ",", "node", "=", "node", ")", "elif", "isinstance", "(", "node", ".", "args", "[", "format_pos", "]", ",", "astroid", ".", "Call", ")", ":", "self", ".", "_check_call_func", "(", "node", ".", "args", "[", "format_pos", "]", ")", "elif", "isinstance", "(", "node", ".", "args", "[", "format_pos", "]", ",", "astroid", ".", "Const", ")", ":", "self", ".", "_check_format_string", "(", "node", ",", "format_pos", ")", "elif", "isinstance", "(", "node", ".", "args", "[", "format_pos", "]", ",", "(", "astroid", ".", "FormattedValue", ",", "astroid", ".", "JoinedStr", ")", ")", ":", "self", ".", "add_message", "(", "\"logging-fstring-interpolation\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker._check_call_func
Checks that function call is not format_string.format(). Args: node (astroid.node_classes.Call): Call AST node to be checked.
pylint/checkers/logging.py
def _check_call_func(self, node): """Checks that function call is not format_string.format(). Args: node (astroid.node_classes.Call): Call AST node to be checked. """ func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if is_method_call(func, types, methods) and not is_complex_format_str( func.bound ): self.add_message("logging-format-interpolation", node=node)
def _check_call_func(self, node): """Checks that function call is not format_string.format(). Args: node (astroid.node_classes.Call): Call AST node to be checked. """ func = utils.safe_infer(node.func) types = ("str", "unicode") methods = ("format",) if is_method_call(func, types, methods) and not is_complex_format_str( func.bound ): self.add_message("logging-format-interpolation", node=node)
[ "Checks", "that", "function", "call", "is", "not", "format_string", ".", "format", "()", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L263-L276
[ "def", "_check_call_func", "(", "self", ",", "node", ")", ":", "func", "=", "utils", ".", "safe_infer", "(", "node", ".", "func", ")", "types", "=", "(", "\"str\"", ",", "\"unicode\"", ")", "methods", "=", "(", "\"format\"", ",", ")", "if", "is_method_call", "(", "func", ",", "types", ",", "methods", ")", "and", "not", "is_complex_format_str", "(", "func", ".", "bound", ")", ":", "self", ".", "add_message", "(", "\"logging-format-interpolation\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
LoggingChecker._check_format_string
Checks that format string tokens match the supplied arguments. Args: node (astroid.node_classes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments.
pylint/checkers/logging.py
def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (astroid.node_classes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value if not isinstance(format_string, str): # If the log format is constant non-string (e.g. logging.debug(5)), # ensure there are no arguments. required_num_args = 0 else: try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": keyword_arguments, implicit_pos_args, explicit_pos_args = utils.parse_format_method_string( format_string ) keyword_args_cnt = len( set(k for k, l in keyword_arguments if not isinstance(k, int)) ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (astroid.node_classes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value if not isinstance(format_string, str): # If the log format is constant non-string (e.g. logging.debug(5)), # ensure there are no arguments. required_num_args = 0 else: try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": keyword_arguments, implicit_pos_args, explicit_pos_args = utils.parse_format_method_string( format_string ) keyword_args_cnt = len( set(k for k, l in keyword_arguments if not isinstance(k, int)) ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
[ "Checks", "that", "format", "string", "tokens", "match", "the", "supplied", "arguments", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/logging.py#L278-L330
[ "def", "_check_format_string", "(", "self", ",", "node", ",", "format_arg", ")", ":", "num_args", "=", "_count_supplied_tokens", "(", "node", ".", "args", "[", "format_arg", "+", "1", ":", "]", ")", "if", "not", "num_args", ":", "# If no args were supplied the string is not interpolated and can contain", "# formatting characters - it's used verbatim. Don't check any further.", "return", "format_string", "=", "node", ".", "args", "[", "format_arg", "]", ".", "value", "if", "not", "isinstance", "(", "format_string", ",", "str", ")", ":", "# If the log format is constant non-string (e.g. logging.debug(5)),", "# ensure there are no arguments.", "required_num_args", "=", "0", "else", ":", "try", ":", "if", "self", ".", "_format_style", "==", "\"old\"", ":", "keyword_args", ",", "required_num_args", ",", "_", ",", "_", "=", "utils", ".", "parse_format_string", "(", "format_string", ")", "if", "keyword_args", ":", "# Keyword checking on logging strings is complicated by", "# special keywords - out of scope.", "return", "elif", "self", ".", "_format_style", "==", "\"new\"", ":", "keyword_arguments", ",", "implicit_pos_args", ",", "explicit_pos_args", "=", "utils", ".", "parse_format_method_string", "(", "format_string", ")", "keyword_args_cnt", "=", "len", "(", "set", "(", "k", "for", "k", ",", "l", "in", "keyword_arguments", "if", "not", "isinstance", "(", "k", ",", "int", ")", ")", ")", "required_num_args", "=", "(", "keyword_args_cnt", "+", "implicit_pos_args", "+", "explicit_pos_args", ")", "except", "utils", ".", "UnsupportedFormatCharacter", "as", "ex", ":", "char", "=", "format_string", "[", "ex", ".", "index", "]", "self", ".", "add_message", "(", "\"logging-unsupported-format\"", ",", "node", "=", "node", ",", "args", "=", "(", "char", ",", "ord", "(", "char", ")", ",", "ex", ".", "index", ")", ",", ")", "return", "except", "utils", ".", "IncompleteFormatString", ":", "self", ".", "add_message", "(", "\"logging-format-truncated\"", ",", "node", "=", "node", ")", "return", "if", "num_args", ">", "required_num_args", ":", "self", ".", "add_message", "(", "\"logging-too-many-args\"", ",", "node", "=", "node", ")", "elif", "num_args", "<", "required_num_args", ":", "self", ".", "add_message", "(", "\"logging-too-few-args\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_redefines_import
Detect that the given node (AssignName) is inside an exception handler and redefines an import from the tryexcept body. Returns True if the node redefines an import, False otherwise.
pylint/checkers/base.py
def _redefines_import(node): """ Detect that the given node (AssignName) is inside an exception handler and redefines an import from the tryexcept body. Returns True if the node redefines an import, False otherwise. """ current = node while current and not isinstance(current.parent, astroid.ExceptHandler): current = current.parent if not current or not utils.error_of_type(current.parent, ImportError): return False try_block = current.parent.parent for import_node in try_block.nodes_of_class((astroid.ImportFrom, astroid.Import)): for name, alias in import_node.names: if alias: if alias == node.name: return True elif name == node.name: return True return False
def _redefines_import(node): """ Detect that the given node (AssignName) is inside an exception handler and redefines an import from the tryexcept body. Returns True if the node redefines an import, False otherwise. """ current = node while current and not isinstance(current.parent, astroid.ExceptHandler): current = current.parent if not current or not utils.error_of_type(current.parent, ImportError): return False try_block = current.parent.parent for import_node in try_block.nodes_of_class((astroid.ImportFrom, astroid.Import)): for name, alias in import_node.names: if alias: if alias == node.name: return True elif name == node.name: return True return False
[ "Detect", "that", "the", "given", "node", "(", "AssignName", ")", "is", "inside", "an", "exception", "handler", "and", "redefines", "an", "import", "from", "the", "tryexcept", "body", ".", "Returns", "True", "if", "the", "node", "redefines", "an", "import", "False", "otherwise", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L178-L196
[ "def", "_redefines_import", "(", "node", ")", ":", "current", "=", "node", "while", "current", "and", "not", "isinstance", "(", "current", ".", "parent", ",", "astroid", ".", "ExceptHandler", ")", ":", "current", "=", "current", ".", "parent", "if", "not", "current", "or", "not", "utils", ".", "error_of_type", "(", "current", ".", "parent", ",", "ImportError", ")", ":", "return", "False", "try_block", "=", "current", ".", "parent", ".", "parent", "for", "import_node", "in", "try_block", ".", "nodes_of_class", "(", "(", "astroid", ".", "ImportFrom", ",", "astroid", ".", "Import", ")", ")", ":", "for", "name", ",", "alias", "in", "import_node", ".", "names", ":", "if", "alias", ":", "if", "alias", "==", "node", ".", "name", ":", "return", "True", "elif", "name", "==", "node", ".", "name", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
in_loop
return True if the node is inside a kind of for loop
pylint/checkers/base.py
def in_loop(node): """return True if the node is inside a kind of for loop""" parent = node.parent while parent is not None: if isinstance( parent, ( astroid.For, astroid.ListComp, astroid.SetComp, astroid.DictComp, astroid.GeneratorExp, ), ): return True parent = parent.parent return False
def in_loop(node): """return True if the node is inside a kind of for loop""" parent = node.parent while parent is not None: if isinstance( parent, ( astroid.For, astroid.ListComp, astroid.SetComp, astroid.DictComp, astroid.GeneratorExp, ), ): return True parent = parent.parent return False
[ "return", "True", "if", "the", "node", "is", "inside", "a", "kind", "of", "for", "loop" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L199-L215
[ "def", "in_loop", "(", "node", ")", ":", "parent", "=", "node", ".", "parent", "while", "parent", "is", "not", "None", ":", "if", "isinstance", "(", "parent", ",", "(", "astroid", ".", "For", ",", "astroid", ".", "ListComp", ",", "astroid", ".", "SetComp", ",", "astroid", ".", "DictComp", ",", "astroid", ".", "GeneratorExp", ",", ")", ",", ")", ":", "return", "True", "parent", "=", "parent", ".", "parent", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
in_nested_list
return true if the object is an element of <nested_list> or of a nested list
pylint/checkers/base.py
def in_nested_list(nested_list, obj): """return true if the object is an element of <nested_list> or of a nested list """ for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: return True return False
def in_nested_list(nested_list, obj): """return true if the object is an element of <nested_list> or of a nested list """ for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: return True return False
[ "return", "true", "if", "the", "object", "is", "an", "element", "of", "<nested_list", ">", "or", "of", "a", "nested", "list" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L218-L228
[ "def", "in_nested_list", "(", "nested_list", ",", "obj", ")", ":", "for", "elmt", "in", "nested_list", ":", "if", "isinstance", "(", "elmt", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "in_nested_list", "(", "elmt", ",", "obj", ")", ":", "return", "True", "elif", "elmt", "==", "obj", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_break_loop_node
Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node.
pylint/checkers/base.py
def _get_break_loop_node(break_node): """ Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node. """ loop_nodes = (astroid.For, astroid.While) parent = break_node.parent while not isinstance(parent, loop_nodes) or break_node in getattr( parent, "orelse", [] ): break_node = parent parent = parent.parent if parent is None: break return parent
def _get_break_loop_node(break_node): """ Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node. """ loop_nodes = (astroid.For, astroid.While) parent = break_node.parent while not isinstance(parent, loop_nodes) or break_node in getattr( parent, "orelse", [] ): break_node = parent parent = parent.parent if parent is None: break return parent
[ "Returns", "the", "loop", "node", "that", "holds", "the", "break", "node", "in", "arguments", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L231-L250
[ "def", "_get_break_loop_node", "(", "break_node", ")", ":", "loop_nodes", "=", "(", "astroid", ".", "For", ",", "astroid", ".", "While", ")", "parent", "=", "break_node", ".", "parent", "while", "not", "isinstance", "(", "parent", ",", "loop_nodes", ")", "or", "break_node", "in", "getattr", "(", "parent", ",", "\"orelse\"", ",", "[", "]", ")", ":", "break_node", "=", "parent", "parent", "=", "parent", ".", "parent", "if", "parent", "is", "None", ":", "break", "return", "parent" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_loop_exits_early
Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise.
pylint/checkers/base.py
def _loop_exits_early(loop): """ Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise. """ loop_nodes = (astroid.For, astroid.While) definition_nodes = (astroid.FunctionDef, astroid.ClassDef) inner_loop_nodes = [ _node for _node in loop.nodes_of_class(loop_nodes, skip_klass=definition_nodes) if _node != loop ] return any( _node for _node in loop.nodes_of_class(astroid.Break, skip_klass=definition_nodes) if _get_break_loop_node(_node) not in inner_loop_nodes )
def _loop_exits_early(loop): """ Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise. """ loop_nodes = (astroid.For, astroid.While) definition_nodes = (astroid.FunctionDef, astroid.ClassDef) inner_loop_nodes = [ _node for _node in loop.nodes_of_class(loop_nodes, skip_klass=definition_nodes) if _node != loop ] return any( _node for _node in loop.nodes_of_class(astroid.Break, skip_klass=definition_nodes) if _get_break_loop_node(_node) not in inner_loop_nodes )
[ "Returns", "true", "if", "a", "loop", "may", "ends", "up", "in", "a", "break", "statement", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L253-L274
[ "def", "_loop_exits_early", "(", "loop", ")", ":", "loop_nodes", "=", "(", "astroid", ".", "For", ",", "astroid", ".", "While", ")", "definition_nodes", "=", "(", "astroid", ".", "FunctionDef", ",", "astroid", ".", "ClassDef", ")", "inner_loop_nodes", "=", "[", "_node", "for", "_node", "in", "loop", ".", "nodes_of_class", "(", "loop_nodes", ",", "skip_klass", "=", "definition_nodes", ")", "if", "_node", "!=", "loop", "]", "return", "any", "(", "_node", "for", "_node", "in", "loop", ".", "nodes_of_class", "(", "astroid", ".", "Break", ",", "skip_klass", "=", "definition_nodes", ")", "if", "_get_break_loop_node", "(", "_node", ")", "not", "in", "inner_loop_nodes", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_get_properties
Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'.
pylint/checkers/base.py
def _get_properties(config): """Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'. """ property_classes = {BUILTIN_PROPERTY} property_names = set() # Not returning 'property', it has its own check. if config is not None: property_classes.update(config.property_classes) property_names.update( (prop.rsplit(".", 1)[-1] for prop in config.property_classes) ) return property_classes, property_names
def _get_properties(config): """Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'. """ property_classes = {BUILTIN_PROPERTY} property_names = set() # Not returning 'property', it has its own check. if config is not None: property_classes.update(config.property_classes) property_names.update( (prop.rsplit(".", 1)[-1] for prop in config.property_classes) ) return property_classes, property_names
[ "Returns", "a", "tuple", "of", "property", "classes", "and", "names", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L289-L302
[ "def", "_get_properties", "(", "config", ")", ":", "property_classes", "=", "{", "BUILTIN_PROPERTY", "}", "property_names", "=", "set", "(", ")", "# Not returning 'property', it has its own check.", "if", "config", "is", "not", "None", ":", "property_classes", ".", "update", "(", "config", ".", "property_classes", ")", "property_names", ".", "update", "(", "(", "prop", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "-", "1", "]", "for", "prop", "in", "config", ".", "property_classes", ")", ")", "return", "property_classes", ",", "property_names" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_determine_function_name_type
Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`optparse.Values` :returns: One of ('function', 'method', 'attr') :rtype: str
pylint/checkers/base.py
def _determine_function_name_type(node, config=None): """Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`optparse.Values` :returns: One of ('function', 'method', 'attr') :rtype: str """ property_classes, property_names = _get_properties(config) if not node.is_method(): return "function" if node.decorators: decorators = node.decorators.nodes else: decorators = [] for decorator in decorators: # If the function is a property (decorated with @property # or @abc.abstractproperty), the name type is 'attr'. if isinstance(decorator, astroid.Name) or ( isinstance(decorator, astroid.Attribute) and decorator.attrname in property_names ): infered = utils.safe_infer(decorator) if infered and infered.qname() in property_classes: return "attr" # If the function is decorated using the prop_method.{setter,getter} # form, treat it like an attribute as well. elif isinstance(decorator, astroid.Attribute) and decorator.attrname in ( "setter", "deleter", ): return "attr" return "method"
def _determine_function_name_type(node, config=None): """Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`optparse.Values` :returns: One of ('function', 'method', 'attr') :rtype: str """ property_classes, property_names = _get_properties(config) if not node.is_method(): return "function" if node.decorators: decorators = node.decorators.nodes else: decorators = [] for decorator in decorators: # If the function is a property (decorated with @property # or @abc.abstractproperty), the name type is 'attr'. if isinstance(decorator, astroid.Name) or ( isinstance(decorator, astroid.Attribute) and decorator.attrname in property_names ): infered = utils.safe_infer(decorator) if infered and infered.qname() in property_classes: return "attr" # If the function is decorated using the prop_method.{setter,getter} # form, treat it like an attribute as well. elif isinstance(decorator, astroid.Attribute) and decorator.attrname in ( "setter", "deleter", ): return "attr" return "method"
[ "Determine", "the", "name", "type", "whose", "regex", "the", "a", "function", "s", "name", "should", "match", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L305-L340
[ "def", "_determine_function_name_type", "(", "node", ",", "config", "=", "None", ")", ":", "property_classes", ",", "property_names", "=", "_get_properties", "(", "config", ")", "if", "not", "node", ".", "is_method", "(", ")", ":", "return", "\"function\"", "if", "node", ".", "decorators", ":", "decorators", "=", "node", ".", "decorators", ".", "nodes", "else", ":", "decorators", "=", "[", "]", "for", "decorator", "in", "decorators", ":", "# If the function is a property (decorated with @property", "# or @abc.abstractproperty), the name type is 'attr'.", "if", "isinstance", "(", "decorator", ",", "astroid", ".", "Name", ")", "or", "(", "isinstance", "(", "decorator", ",", "astroid", ".", "Attribute", ")", "and", "decorator", ".", "attrname", "in", "property_names", ")", ":", "infered", "=", "utils", ".", "safe_infer", "(", "decorator", ")", "if", "infered", "and", "infered", ".", "qname", "(", ")", "in", "property_classes", ":", "return", "\"attr\"", "# If the function is decorated using the prop_method.{setter,getter}", "# form, treat it like an attribute as well.", "elif", "isinstance", "(", "decorator", ",", "astroid", ".", "Attribute", ")", "and", "decorator", ".", "attrname", "in", "(", "\"setter\"", ",", "\"deleter\"", ",", ")", ":", "return", "\"attr\"", "return", "\"method\"" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
report_by_type_stats
make a report of * percentage of different types documented * percentage of different types with a bad name
pylint/checkers/base.py
def report_by_type_stats(sect, stats, _): """make a report of * percentage of different types documented * percentage of different types with a bad name """ # percentage of different types documented and/or with a bad name nice_stats = {} for node_type in ("module", "class", "method", "function"): try: total = stats[node_type] except KeyError: raise exceptions.EmptyReportError() nice_stats[node_type] = {} if total != 0: try: documented = total - stats["undocumented_" + node_type] percent = (documented * 100.0) / total nice_stats[node_type]["percent_documented"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_documented"] = "NC" try: percent = (stats["badname_" + node_type] * 100.0) / total nice_stats[node_type]["percent_badname"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_badname"] = "NC" lines = ("type", "number", "old number", "difference", "%documented", "%badname") for node_type in ("module", "class", "method", "function"): new = stats[node_type] lines += ( node_type, str(new), "NC", "NC", nice_stats[node_type].get("percent_documented", "0"), nice_stats[node_type].get("percent_badname", "0"), ) sect.append(reporter_nodes.Table(children=lines, cols=6, rheaders=1))
def report_by_type_stats(sect, stats, _): """make a report of * percentage of different types documented * percentage of different types with a bad name """ # percentage of different types documented and/or with a bad name nice_stats = {} for node_type in ("module", "class", "method", "function"): try: total = stats[node_type] except KeyError: raise exceptions.EmptyReportError() nice_stats[node_type] = {} if total != 0: try: documented = total - stats["undocumented_" + node_type] percent = (documented * 100.0) / total nice_stats[node_type]["percent_documented"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_documented"] = "NC" try: percent = (stats["badname_" + node_type] * 100.0) / total nice_stats[node_type]["percent_badname"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_badname"] = "NC" lines = ("type", "number", "old number", "difference", "%documented", "%badname") for node_type in ("module", "class", "method", "function"): new = stats[node_type] lines += ( node_type, str(new), "NC", "NC", nice_stats[node_type].get("percent_documented", "0"), nice_stats[node_type].get("percent_badname", "0"), ) sect.append(reporter_nodes.Table(children=lines, cols=6, rheaders=1))
[ "make", "a", "report", "of" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L353-L390
[ "def", "report_by_type_stats", "(", "sect", ",", "stats", ",", "_", ")", ":", "# percentage of different types documented and/or with a bad name", "nice_stats", "=", "{", "}", "for", "node_type", "in", "(", "\"module\"", ",", "\"class\"", ",", "\"method\"", ",", "\"function\"", ")", ":", "try", ":", "total", "=", "stats", "[", "node_type", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "EmptyReportError", "(", ")", "nice_stats", "[", "node_type", "]", "=", "{", "}", "if", "total", "!=", "0", ":", "try", ":", "documented", "=", "total", "-", "stats", "[", "\"undocumented_\"", "+", "node_type", "]", "percent", "=", "(", "documented", "*", "100.0", ")", "/", "total", "nice_stats", "[", "node_type", "]", "[", "\"percent_documented\"", "]", "=", "\"%.2f\"", "%", "percent", "except", "KeyError", ":", "nice_stats", "[", "node_type", "]", "[", "\"percent_documented\"", "]", "=", "\"NC\"", "try", ":", "percent", "=", "(", "stats", "[", "\"badname_\"", "+", "node_type", "]", "*", "100.0", ")", "/", "total", "nice_stats", "[", "node_type", "]", "[", "\"percent_badname\"", "]", "=", "\"%.2f\"", "%", "percent", "except", "KeyError", ":", "nice_stats", "[", "node_type", "]", "[", "\"percent_badname\"", "]", "=", "\"NC\"", "lines", "=", "(", "\"type\"", ",", "\"number\"", ",", "\"old number\"", ",", "\"difference\"", ",", "\"%documented\"", ",", "\"%badname\"", ")", "for", "node_type", "in", "(", "\"module\"", ",", "\"class\"", ",", "\"method\"", ",", "\"function\"", ")", ":", "new", "=", "stats", "[", "node_type", "]", "lines", "+=", "(", "node_type", ",", "str", "(", "new", ")", ",", "\"NC\"", ",", "\"NC\"", ",", "nice_stats", "[", "node_type", "]", ".", "get", "(", "\"percent_documented\"", ",", "\"0\"", ")", ",", "nice_stats", "[", "node_type", "]", ".", "get", "(", "\"percent_badname\"", ",", "\"0\"", ")", ",", ")", "sect", ".", "append", "(", "reporter_nodes", ".", "Table", "(", "children", "=", "lines", ",", "cols", "=", "6", ",", "rheaders", "=", "1", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
redefined_by_decorator
return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value
pylint/checkers/base.py
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: if ( isinstance(decorator, astroid.Attribute) and getattr(decorator.expr, "name", None) == node.name ): return True return False
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: if ( isinstance(decorator, astroid.Attribute) and getattr(decorator.expr, "name", None) == node.name ): return True return False
[ "return", "True", "if", "the", "object", "is", "a", "method", "redefined", "via", "decorator", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L393-L409
[ "def", "redefined_by_decorator", "(", "node", ")", ":", "if", "node", ".", "decorators", ":", "for", "decorator", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "(", "isinstance", "(", "decorator", ",", "astroid", ".", "Attribute", ")", "and", "getattr", "(", "decorator", ".", "expr", ",", "\"name\"", ",", "None", ")", "==", "node", ".", "name", ")", ":", "return", "True", "return", "False" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
_is_one_arg_pos_call
Is this a call with exactly 1 argument, where that argument is positional?
pylint/checkers/base.py
def _is_one_arg_pos_call(call): """Is this a call with exactly 1 argument, where that argument is positional? """ return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords
def _is_one_arg_pos_call(call): """Is this a call with exactly 1 argument, where that argument is positional? """ return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords
[ "Is", "this", "a", "call", "with", "exactly", "1", "argument", "where", "that", "argument", "is", "positional?" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L2021-L2025
[ "def", "_is_one_arg_pos_call", "(", "call", ")", ":", "return", "isinstance", "(", "call", ",", "astroid", ".", "Call", ")", "and", "len", "(", "call", ".", "args", ")", "==", "1", "and", "not", "call", ".", "keywords" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
register
required method to auto register this checker
pylint/checkers/base.py
def register(linter): """required method to auto register this checker""" linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) linter.register_checker(NameChecker(linter)) linter.register_checker(DocStringChecker(linter)) linter.register_checker(PassChecker(linter)) linter.register_checker(ComparisonChecker(linter))
def register(linter): """required method to auto register this checker""" linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) linter.register_checker(NameChecker(linter)) linter.register_checker(DocStringChecker(linter)) linter.register_checker(PassChecker(linter)) linter.register_checker(ComparisonChecker(linter))
[ "required", "method", "to", "auto", "register", "this", "checker" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L2236-L2243
[ "def", "register", "(", "linter", ")", ":", "linter", ".", "register_checker", "(", "BasicErrorChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "BasicChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "NameChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "DocStringChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "PassChecker", "(", "linter", ")", ")", "linter", ".", "register_checker", "(", "ComparisonChecker", "(", "linter", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker.visit_starred
Check that a Starred expression is used in an assignment target.
pylint/checkers/base.py
def visit_starred(self, node): """Check that a Starred expression is used in an assignment target.""" if isinstance(node.parent, astroid.Call): # f(*args) is converted to Call(args=[Starred]), so ignore # them for this check. return if PY35 and isinstance( node.parent, (astroid.List, astroid.Tuple, astroid.Set, astroid.Dict) ): # PEP 448 unpacking. return stmt = node.statement() if not isinstance(stmt, astroid.Assign): return if stmt.value is node or stmt.value.parent_of(node): self.add_message("star-needs-assignment-target", node=node)
def visit_starred(self, node): """Check that a Starred expression is used in an assignment target.""" if isinstance(node.parent, astroid.Call): # f(*args) is converted to Call(args=[Starred]), so ignore # them for this check. return if PY35 and isinstance( node.parent, (astroid.List, astroid.Tuple, astroid.Set, astroid.Dict) ): # PEP 448 unpacking. return stmt = node.statement() if not isinstance(stmt, astroid.Assign): return if stmt.value is node or stmt.value.parent_of(node): self.add_message("star-needs-assignment-target", node=node)
[ "Check", "that", "a", "Starred", "expression", "is", "used", "in", "an", "assignment", "target", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L552-L569
[ "def", "visit_starred", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ".", "parent", ",", "astroid", ".", "Call", ")", ":", "# f(*args) is converted to Call(args=[Starred]), so ignore", "# them for this check.", "return", "if", "PY35", "and", "isinstance", "(", "node", ".", "parent", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ",", "astroid", ".", "Set", ",", "astroid", ".", "Dict", ")", ")", ":", "# PEP 448 unpacking.", "return", "stmt", "=", "node", ".", "statement", "(", ")", "if", "not", "isinstance", "(", "stmt", ",", "astroid", ".", "Assign", ")", ":", "return", "if", "stmt", ".", "value", "is", "node", "or", "stmt", ".", "value", ".", "parent_of", "(", "node", ")", ":", "self", ".", "add_message", "(", "\"star-needs-assignment-target\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker._check_nonlocal_and_global
Check that a name is both nonlocal and global.
pylint/checkers/base.py
def _check_nonlocal_and_global(self, node): """Check that a name is both nonlocal and global.""" def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(astroid.Nonlocal) if same_scope(child) ) ) if not nonlocals: return global_vars = set( from_iter( child.names for child in node.nodes_of_class(astroid.Global) if same_scope(child) ) ) for name in nonlocals.intersection(global_vars): self.add_message("nonlocal-and-global", args=(name,), node=node)
def _check_nonlocal_and_global(self, node): """Check that a name is both nonlocal and global.""" def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(astroid.Nonlocal) if same_scope(child) ) ) if not nonlocals: return global_vars = set( from_iter( child.names for child in node.nodes_of_class(astroid.Global) if same_scope(child) ) ) for name in nonlocals.intersection(global_vars): self.add_message("nonlocal-and-global", args=(name,), node=node)
[ "Check", "that", "a", "name", "is", "both", "nonlocal", "and", "global", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L659-L685
[ "def", "_check_nonlocal_and_global", "(", "self", ",", "node", ")", ":", "def", "same_scope", "(", "current", ")", ":", "return", "current", ".", "scope", "(", ")", "is", "node", "from_iter", "=", "itertools", ".", "chain", ".", "from_iterable", "nonlocals", "=", "set", "(", "from_iter", "(", "child", ".", "names", "for", "child", "in", "node", ".", "nodes_of_class", "(", "astroid", ".", "Nonlocal", ")", "if", "same_scope", "(", "child", ")", ")", ")", "if", "not", "nonlocals", ":", "return", "global_vars", "=", "set", "(", "from_iter", "(", "child", ".", "names", "for", "child", "in", "node", ".", "nodes_of_class", "(", "astroid", ".", "Global", ")", "if", "same_scope", "(", "child", ")", ")", ")", "for", "name", "in", "nonlocals", ".", "intersection", "(", "global_vars", ")", ":", "self", ".", "add_message", "(", "\"nonlocal-and-global\"", ",", "args", "=", "(", "name", ",", ")", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker.visit_unaryop
check use of the non-existent ++ and -- operator operator
pylint/checkers/base.py
def visit_unaryop(self, node): """check use of the non-existent ++ and -- operator operator""" if ( (node.op in "+-") and isinstance(node.operand, astroid.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2)
def visit_unaryop(self, node): """check use of the non-existent ++ and -- operator operator""" if ( (node.op in "+-") and isinstance(node.operand, astroid.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=node, args=node.op * 2)
[ "check", "use", "of", "the", "non", "-", "existent", "++", "and", "--", "operator", "operator" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L717-L724
[ "def", "visit_unaryop", "(", "self", ",", "node", ")", ":", "if", "(", "(", "node", ".", "op", "in", "\"+-\"", ")", "and", "isinstance", "(", "node", ".", "operand", ",", "astroid", ".", "UnaryOp", ")", "and", "(", "node", ".", "operand", ".", "op", "==", "node", ".", "op", ")", ")", ":", "self", ".", "add_message", "(", "\"nonexistent-operator\"", ",", "node", "=", "node", ",", "args", "=", "node", ".", "op", "*", "2", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker.visit_call
Check instantiating abstract class with abc.ABCMeta as metaclass.
pylint/checkers/base.py
def visit_call(self, node): """ Check instantiating abstract class with abc.ABCMeta as metaclass. """ try: for inferred in node.func.infer(): self._check_inferred_class_is_abstract(inferred, node) except astroid.InferenceError: return
def visit_call(self, node): """ Check instantiating abstract class with abc.ABCMeta as metaclass. """ try: for inferred in node.func.infer(): self._check_inferred_class_is_abstract(inferred, node) except astroid.InferenceError: return
[ "Check", "instantiating", "abstract", "class", "with", "abc", ".", "ABCMeta", "as", "metaclass", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L752-L760
[ "def", "visit_call", "(", "self", ",", "node", ")", ":", "try", ":", "for", "inferred", "in", "node", ".", "func", ".", "infer", "(", ")", ":", "self", ".", "_check_inferred_class_is_abstract", "(", "inferred", ",", "node", ")", "except", "astroid", ".", "InferenceError", ":", "return" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker._check_else_on_loop
Check that any loop with an else clause has a break statement.
pylint/checkers/base.py
def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, )
def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, )
[ "Check", "that", "any", "loop", "with", "an", "else", "clause", "has", "a", "break", "statement", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L803-L813
[ "def", "_check_else_on_loop", "(", "self", ",", "node", ")", ":", "if", "node", ".", "orelse", "and", "not", "_loop_exits_early", "(", "node", ")", ":", "self", ".", "add_message", "(", "\"useless-else-on-loop\"", ",", "node", "=", "node", ",", "# This is not optimal, but the line previous", "# to the first statement in the else clause", "# will usually be the one that contains the else:.", "line", "=", "node", ".", "orelse", "[", "0", "]", ".", "lineno", "-", "1", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker._check_in_loop
check that a node is inside a for or while loop
pylint/checkers/base.py
def _check_in_loop(self, node, node_name): """check that a node is inside a for or while loop""" _node = node.parent while _node: if isinstance(_node, (astroid.For, astroid.While)): if node not in _node.orelse: return if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)): break if ( isinstance(_node, astroid.TryFinally) and node in _node.finalbody and isinstance(node, astroid.Continue) ): self.add_message("continue-in-finally", node=node) _node = _node.parent self.add_message("not-in-loop", node=node, args=node_name)
def _check_in_loop(self, node, node_name): """check that a node is inside a for or while loop""" _node = node.parent while _node: if isinstance(_node, (astroid.For, astroid.While)): if node not in _node.orelse: return if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)): break if ( isinstance(_node, astroid.TryFinally) and node in _node.finalbody and isinstance(node, astroid.Continue) ): self.add_message("continue-in-finally", node=node) _node = _node.parent self.add_message("not-in-loop", node=node, args=node_name)
[ "check", "that", "a", "node", "is", "inside", "a", "for", "or", "while", "loop" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L815-L834
[ "def", "_check_in_loop", "(", "self", ",", "node", ",", "node_name", ")", ":", "_node", "=", "node", ".", "parent", "while", "_node", ":", "if", "isinstance", "(", "_node", ",", "(", "astroid", ".", "For", ",", "astroid", ".", "While", ")", ")", ":", "if", "node", "not", "in", "_node", ".", "orelse", ":", "return", "if", "isinstance", "(", "_node", ",", "(", "astroid", ".", "ClassDef", ",", "astroid", ".", "FunctionDef", ")", ")", ":", "break", "if", "(", "isinstance", "(", "_node", ",", "astroid", ".", "TryFinally", ")", "and", "node", "in", "_node", ".", "finalbody", "and", "isinstance", "(", "node", ",", "astroid", ".", "Continue", ")", ")", ":", "self", ".", "add_message", "(", "\"continue-in-finally\"", ",", "node", "=", "node", ")", "_node", "=", "_node", ".", "parent", "self", ".", "add_message", "(", "\"not-in-loop\"", ",", "node", "=", "node", ",", "args", "=", "node_name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicErrorChecker._check_redefinition
check for redefinition of a function / method / class name
pylint/checkers/base.py
def _check_redefinition(self, redeftype, node): """check for redefinition of a function / method / class name""" parent_frame = node.parent.frame() defined_self = parent_frame[node.name] if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, astroid.ClassDef) and node.name in REDEFINABLE_METHODS ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
def _check_redefinition(self, redeftype, node): """check for redefinition of a function / method / class name""" parent_frame = node.parent.frame() defined_self = parent_frame[node.name] if defined_self is not node and not astroid.are_exclusive(node, defined_self): # Additional checks for methods which are not considered # redefined, since they are already part of the base API. if ( isinstance(parent_frame, astroid.ClassDef) and node.name in REDEFINABLE_METHODS ): return dummy_variables_rgx = lint_utils.get_global_option( self, "dummy-variables-rgx", default=None ) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message( "function-redefined", node=node, args=(redeftype, defined_self.fromlineno), )
[ "check", "for", "redefinition", "of", "a", "function", "/", "method", "/", "class", "name" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L836-L859
[ "def", "_check_redefinition", "(", "self", ",", "redeftype", ",", "node", ")", ":", "parent_frame", "=", "node", ".", "parent", ".", "frame", "(", ")", "defined_self", "=", "parent_frame", "[", "node", ".", "name", "]", "if", "defined_self", "is", "not", "node", "and", "not", "astroid", ".", "are_exclusive", "(", "node", ",", "defined_self", ")", ":", "# Additional checks for methods which are not considered", "# redefined, since they are already part of the base API.", "if", "(", "isinstance", "(", "parent_frame", ",", "astroid", ".", "ClassDef", ")", "and", "node", ".", "name", "in", "REDEFINABLE_METHODS", ")", ":", "return", "dummy_variables_rgx", "=", "lint_utils", ".", "get_global_option", "(", "self", ",", "\"dummy-variables-rgx\"", ",", "default", "=", "None", ")", "if", "dummy_variables_rgx", "and", "dummy_variables_rgx", ".", "match", "(", "node", ".", "name", ")", ":", "return", "self", ".", "add_message", "(", "\"function-redefined\"", ",", "node", "=", "node", ",", "args", "=", "(", "redeftype", ",", "defined_self", ".", "fromlineno", ")", ",", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.open
initialize visit variables and statistics
pylint/checkers/base.py
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
[ "initialize", "visit", "variables", "and", "statistics" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L997-L1001
[ "def", "open", "(", "self", ")", ":", "self", ".", "_tryfinallys", "=", "[", "]", "self", ".", "stats", "=", "self", ".", "linter", ".", "add_stats", "(", "module", "=", "0", ",", "function", "=", "0", ",", "method", "=", "0", ",", "class_", "=", "0", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_expr
check for various kind of statements without effect
pylint/checkers/base.py
def visit_expr(self, node): """check for various kind of statements without effect""" expr = node.value if isinstance(expr, astroid.Const) and isinstance(expr.value, str): # treat string statement in a separated message # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance( scope, (astroid.ClassDef, astroid.Module, astroid.FunctionDef) ): if isinstance(scope, astroid.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (astroid.Assign, astroid.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yieldd statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if isinstance( expr, (astroid.Yield, astroid.Await, astroid.Ellipsis, astroid.Call) ) or ( isinstance(node.parent, astroid.TryExcept) and node.parent.body == [node] ): return if any(expr.nodes_of_class(astroid.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node)
def visit_expr(self, node): """check for various kind of statements without effect""" expr = node.value if isinstance(expr, astroid.Const) and isinstance(expr.value, str): # treat string statement in a separated message # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance( scope, (astroid.ClassDef, astroid.Module, astroid.FunctionDef) ): if isinstance(scope, astroid.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (astroid.Assign, astroid.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yieldd statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if isinstance( expr, (astroid.Yield, astroid.Await, astroid.Ellipsis, astroid.Call) ) or ( isinstance(node.parent, astroid.TryExcept) and node.parent.body == [node] ): return if any(expr.nodes_of_class(astroid.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node)
[ "check", "for", "various", "kind", "of", "statements", "without", "effect" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1081-L1124
[ "def", "visit_expr", "(", "self", ",", "node", ")", ":", "expr", "=", "node", ".", "value", "if", "isinstance", "(", "expr", ",", "astroid", ".", "Const", ")", "and", "isinstance", "(", "expr", ".", "value", ",", "str", ")", ":", "# treat string statement in a separated message", "# Handle PEP-257 attribute docstrings.", "# An attribute docstring is defined as being a string right after", "# an assignment at the module level, class level or __init__ level.", "scope", "=", "expr", ".", "scope", "(", ")", "if", "isinstance", "(", "scope", ",", "(", "astroid", ".", "ClassDef", ",", "astroid", ".", "Module", ",", "astroid", ".", "FunctionDef", ")", ")", ":", "if", "isinstance", "(", "scope", ",", "astroid", ".", "FunctionDef", ")", "and", "scope", ".", "name", "!=", "\"__init__\"", ":", "pass", "else", ":", "sibling", "=", "expr", ".", "previous_sibling", "(", ")", "if", "(", "sibling", "is", "not", "None", "and", "sibling", ".", "scope", "(", ")", "is", "scope", "and", "isinstance", "(", "sibling", ",", "(", "astroid", ".", "Assign", ",", "astroid", ".", "AnnAssign", ")", ")", ")", ":", "return", "self", ".", "add_message", "(", "\"pointless-string-statement\"", ",", "node", "=", "node", ")", "return", "# Ignore if this is :", "# * a direct function call", "# * the unique child of a try/except body", "# * a yieldd statement", "# * an ellipsis (which can be used on Python 3 instead of pass)", "# warn W0106 if we have any underlying function call (we can't predict", "# side effects), else pointless-statement", "if", "isinstance", "(", "expr", ",", "(", "astroid", ".", "Yield", ",", "astroid", ".", "Await", ",", "astroid", ".", "Ellipsis", ",", "astroid", ".", "Call", ")", ")", "or", "(", "isinstance", "(", "node", ".", "parent", ",", "astroid", ".", "TryExcept", ")", "and", "node", ".", "parent", ".", "body", "==", "[", "node", "]", ")", ":", "return", "if", "any", "(", "expr", ".", "nodes_of_class", "(", "astroid", ".", "Call", ")", ")", ":", "self", ".", "add_message", "(", "\"expression-not-assigned\"", ",", "node", "=", "node", ",", "args", "=", "expr", ".", "as_string", "(", ")", ")", "else", ":", "self", ".", "add_message", "(", "\"pointless-statement\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_lambda
check whether or not the lambda is suspicious
pylint/checkers/base.py
def visit_lambda(self, node): """check whether or not the lambda is suspicious """ # if the body of the lambda is a call expression with the same # argument list as the lambda itself, then the lambda is # possibly unnecessary and at least suspicious. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, astroid.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, astroid.Attribute) and isinstance( node.body.func.expr, astroid.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, astroid.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node)
def visit_lambda(self, node): """check whether or not the lambda is suspicious """ # if the body of the lambda is a call expression with the same # argument list as the lambda itself, then the lambda is # possibly unnecessary and at least suspicious. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, astroid.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, astroid.Attribute) and isinstance( node.body.func.expr, astroid.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, astroid.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node)
[ "check", "whether", "or", "not", "the", "lambda", "is", "suspicious" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1153-L1211
[ "def", "visit_lambda", "(", "self", ",", "node", ")", ":", "# if the body of the lambda is a call expression with the same", "# argument list as the lambda itself, then the lambda is", "# possibly unnecessary and at least suspicious.", "if", "node", ".", "args", ".", "defaults", ":", "# If the arguments of the lambda include defaults, then a", "# judgment cannot be made because there is no way to check", "# that the defaults defined by the lambda are the same as", "# the defaults defined by the function called in the body", "# of the lambda.", "return", "call", "=", "node", ".", "body", "if", "not", "isinstance", "(", "call", ",", "astroid", ".", "Call", ")", ":", "# The body of the lambda must be a function call expression", "# for the lambda to be unnecessary.", "return", "if", "isinstance", "(", "node", ".", "body", ".", "func", ",", "astroid", ".", "Attribute", ")", "and", "isinstance", "(", "node", ".", "body", ".", "func", ".", "expr", ",", "astroid", ".", "Call", ")", ":", "# Chained call, the intermediate call might", "# return something else (but we don't check that, yet).", "return", "call_site", "=", "CallSite", ".", "from_call", "(", "call", ")", "ordinary_args", "=", "list", "(", "node", ".", "args", ".", "args", ")", "new_call_args", "=", "list", "(", "self", ".", "_filter_vararg", "(", "node", ",", "call", ".", "args", ")", ")", "if", "node", ".", "args", ".", "kwarg", ":", "if", "self", ".", "_has_variadic_argument", "(", "call", ".", "kwargs", ",", "node", ".", "args", ".", "kwarg", ")", ":", "return", "if", "node", ".", "args", ".", "vararg", ":", "if", "self", ".", "_has_variadic_argument", "(", "call", ".", "starargs", ",", "node", ".", "args", ".", "vararg", ")", ":", "return", "elif", "call", ".", "starargs", ":", "return", "if", "call", ".", "keywords", ":", "# Look for additional keyword arguments that are not part", "# of the lambda's signature", "lambda_kwargs", "=", "{", "keyword", ".", "name", "for", "keyword", "in", "node", ".", "args", ".", "defaults", "}", "if", "len", "(", "lambda_kwargs", ")", "!=", "len", "(", "call_site", ".", "keyword_arguments", ")", ":", "# Different lengths, so probably not identical", "return", "if", "set", "(", "call_site", ".", "keyword_arguments", ")", ".", "difference", "(", "lambda_kwargs", ")", ":", "return", "# The \"ordinary\" arguments must be in a correspondence such that:", "# ordinary_args[i].name == call.args[i].name.", "if", "len", "(", "ordinary_args", ")", "!=", "len", "(", "new_call_args", ")", ":", "return", "for", "arg", ",", "passed_arg", "in", "zip", "(", "ordinary_args", ",", "new_call_args", ")", ":", "if", "not", "isinstance", "(", "passed_arg", ",", "astroid", ".", "Name", ")", ":", "return", "if", "arg", ".", "name", "!=", "passed_arg", ".", "name", ":", "return", "self", ".", "add_message", "(", "\"unnecessary-lambda\"", ",", "line", "=", "node", ".", "fromlineno", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_functiondef
check function name, docstring, arguments, redefinition, variable names, max locals
pylint/checkers/base.py
def visit_functiondef(self, node): """check function name, docstring, arguments, redefinition, variable names, max locals """ self.stats[node.is_method() and "method" or "function"] += 1 self._check_dangerous_default(node)
def visit_functiondef(self, node): """check function name, docstring, arguments, redefinition, variable names, max locals """ self.stats[node.is_method() and "method" or "function"] += 1 self._check_dangerous_default(node)
[ "check", "function", "name", "docstring", "arguments", "redefinition", "variable", "names", "max", "locals" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1214-L1219
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "self", ".", "stats", "[", "node", ".", "is_method", "(", ")", "and", "\"method\"", "or", "\"function\"", "]", "+=", "1", "self", ".", "_check_dangerous_default", "(", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_return
1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block
pylint/checkers/base.py
def visit_return(self, node): """1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block """ self._check_unreachable(node) # Is it inside final body of a try...finally bloc ? self._check_not_in_finally(node, "return", (astroid.FunctionDef,))
def visit_return(self, node): """1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block """ self._check_unreachable(node) # Is it inside final body of a try...finally bloc ? self._check_not_in_finally(node, "return", (astroid.FunctionDef,))
[ "1", "-", "check", "is", "the", "node", "has", "a", "right", "sibling", "(", "if", "so", "that", "s", "some", "unreachable", "code", ")", "2", "-", "check", "is", "the", "node", "is", "inside", "the", "finally", "clause", "of", "a", "try", "...", "finally", "block" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1262-L1270
[ "def", "visit_return", "(", "self", ",", "node", ")", ":", "self", ".", "_check_unreachable", "(", "node", ")", "# Is it inside final body of a try...finally bloc ?", "self", ".", "_check_not_in_finally", "(", "node", ",", "\"return\"", ",", "(", "astroid", ".", "FunctionDef", ",", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_break
1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block
pylint/checkers/base.py
def visit_break(self, node): """1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally bloc ? self._check_not_in_finally(node, "break", (astroid.For, astroid.While))
def visit_break(self, node): """1 - check is the node has a right sibling (if so, that's some unreachable code) 2 - check is the node is inside the finally clause of a try...finally block """ # 1 - Is it right sibling ? self._check_unreachable(node) # 2 - Is it inside final body of a try...finally bloc ? self._check_not_in_finally(node, "break", (astroid.For, astroid.While))
[ "1", "-", "check", "is", "the", "node", "has", "a", "right", "sibling", "(", "if", "so", "that", "s", "some", "unreachable", "code", ")", "2", "-", "check", "is", "the", "node", "is", "inside", "the", "finally", "clause", "of", "a", "try", "...", "finally", "block" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1280-L1289
[ "def", "visit_break", "(", "self", ",", "node", ")", ":", "# 1 - Is it right sibling ?", "self", ".", "_check_unreachable", "(", "node", ")", "# 2 - Is it inside final body of a try...finally bloc ?", "self", ".", "_check_not_in_finally", "(", "node", ",", "\"break\"", ",", "(", "astroid", ".", "For", ",", "astroid", ".", "While", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_call
visit a Call node -> check if this is not a blacklisted builtin call and check for * or ** use
pylint/checkers/base.py
def visit_call(self, node): """visit a Call node -> check if this is not a blacklisted builtin call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, astroid.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame() or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node)
def visit_call(self, node): """visit a Call node -> check if this is not a blacklisted builtin call and check for * or ** use """ self._check_misplaced_format_function(node) if isinstance(node.func, astroid.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame() or name in node.root()): if name == "exec": self.add_message("exec-used", node=node) elif name == "reversed": self._check_reversed(node) elif name == "eval": self.add_message("eval-used", node=node)
[ "visit", "a", "Call", "node", "-", ">", "check", "if", "this", "is", "not", "a", "blacklisted", "builtin", "call", "and", "check", "for", "*", "or", "**", "use" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1327-L1342
[ "def", "visit_call", "(", "self", ",", "node", ")", ":", "self", ".", "_check_misplaced_format_function", "(", "node", ")", "if", "isinstance", "(", "node", ".", "func", ",", "astroid", ".", "Name", ")", ":", "name", "=", "node", ".", "func", ".", "name", "# ignore the name if it's not a builtin (i.e. not defined in the", "# locals nor globals scope)", "if", "not", "(", "name", "in", "node", ".", "frame", "(", ")", "or", "name", "in", "node", ".", "root", "(", ")", ")", ":", "if", "name", "==", "\"exec\"", ":", "self", ".", "add_message", "(", "\"exec-used\"", ",", "node", "=", "node", ")", "elif", "name", "==", "\"reversed\"", ":", "self", ".", "_check_reversed", "(", "node", ")", "elif", "name", "==", "\"eval\"", ":", "self", ".", "add_message", "(", "\"eval-used\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_assert
check the use of an assert statement on a tuple.
pylint/checkers/base.py
def visit_assert(self, node): """check the use of an assert statement on a tuple.""" if ( node.fail is None and isinstance(node.test, astroid.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node)
def visit_assert(self, node): """check the use of an assert statement on a tuple.""" if ( node.fail is None and isinstance(node.test, astroid.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node)
[ "check", "the", "use", "of", "an", "assert", "statement", "on", "a", "tuple", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1345-L1352
[ "def", "visit_assert", "(", "self", ",", "node", ")", ":", "if", "(", "node", ".", "fail", "is", "None", "and", "isinstance", "(", "node", ".", "test", ",", "astroid", ".", "Tuple", ")", "and", "len", "(", "node", ".", "test", ".", "elts", ")", "==", "2", ")", ":", "self", ".", "add_message", "(", "\"assert-on-tuple\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker.visit_dict
check duplicate key in dictionary
pylint/checkers/base.py
def visit_dict(self, node): """check duplicate key in dictionary""" keys = set() for k, _ in node.items: if isinstance(k, astroid.Const): key = k.value if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key)
def visit_dict(self, node): """check duplicate key in dictionary""" keys = set() for k, _ in node.items: if isinstance(k, astroid.Const): key = k.value if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key)
[ "check", "duplicate", "key", "in", "dictionary" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1355-L1363
[ "def", "visit_dict", "(", "self", ",", "node", ")", ":", "keys", "=", "set", "(", ")", "for", "k", ",", "_", "in", "node", ".", "items", ":", "if", "isinstance", "(", "k", ",", "astroid", ".", "Const", ")", ":", "key", "=", "k", ".", "value", "if", "key", "in", "keys", ":", "self", ".", "add_message", "(", "\"duplicate-key\"", ",", "node", "=", "node", ",", "args", "=", "key", ")", "keys", ".", "add", "(", "key", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker._check_unreachable
check unreachable code
pylint/checkers/base.py
def _check_unreachable(self, node): """check unreachable code""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: self.add_message("unreachable", node=unreach_stmt)
def _check_unreachable(self, node): """check unreachable code""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: self.add_message("unreachable", node=unreach_stmt)
[ "check", "unreachable", "code" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1373-L1377
[ "def", "_check_unreachable", "(", "self", ",", "node", ")", ":", "unreach_stmt", "=", "node", ".", "next_sibling", "(", ")", "if", "unreach_stmt", "is", "not", "None", ":", "self", ".", "add_message", "(", "\"unreachable\"", ",", "node", "=", "unreach_stmt", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker._check_not_in_finally
check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.
pylint/checkers/base.py
def _check_not_in_finally(self, node, node_name, breaker_classes=()): """check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.""" # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-children of the try...finally _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent
def _check_not_in_finally(self, node, node_name, breaker_classes=()): """check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.""" # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-children of the try...finally _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent
[ "check", "that", "a", "node", "is", "not", "inside", "a", "finally", "clause", "of", "a", "try", "...", "finally", "statement", ".", "If", "we", "found", "before", "a", "try", "...", "finally", "bloc", "a", "parent", "which", "its", "type", "is", "in", "breaker_classes", "we", "skip", "the", "whole", "check", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1379-L1395
[ "def", "_check_not_in_finally", "(", "self", ",", "node", ",", "node_name", ",", "breaker_classes", "=", "(", ")", ")", ":", "# if self._tryfinallys is empty, we're not an in try...finally block", "if", "not", "self", ".", "_tryfinallys", ":", "return", "# the node could be a grand-grand...-children of the try...finally", "_parent", "=", "node", ".", "parent", "_node", "=", "node", "while", "_parent", "and", "not", "isinstance", "(", "_parent", ",", "breaker_classes", ")", ":", "if", "hasattr", "(", "_parent", ",", "\"finalbody\"", ")", "and", "_node", "in", "_parent", ".", "finalbody", ":", "self", ".", "add_message", "(", "\"lost-exception\"", ",", "node", "=", "node", ",", "args", "=", "node_name", ")", "return", "_node", "=", "_parent", "_parent", "=", "_node", ".", "parent" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
BasicChecker._check_reversed
check that the argument to `reversed` is a sequence
pylint/checkers/base.py
def _check_reversed(self, node): """ check that the argument to `reversed` is a sequence """ try: argument = utils.safe_infer(utils.get_argument_from_call(node, position=0)) except utils.NoSuchArgumentError: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was infered. # Try to see if we have iter(). if isinstance(node.args[0], astroid.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (astroid.List, astroid.Tuple)): return if isinstance(argument, astroid.Instance): if argument._proxied.name == "dict" and utils.is_builtin_object( argument._proxied ): self.add_message("bad-reversed-sequence", node=node) return if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in argument._proxied.ancestors() ): # Mappings aren't accepted by reversed(), unless # they provide explicitly a __reversed__ method. try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node)
def _check_reversed(self, node): """ check that the argument to `reversed` is a sequence """ try: argument = utils.safe_infer(utils.get_argument_from_call(node, position=0)) except utils.NoSuchArgumentError: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was infered. # Try to see if we have iter(). if isinstance(node.args[0], astroid.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (astroid.List, astroid.Tuple)): return if isinstance(argument, astroid.Instance): if argument._proxied.name == "dict" and utils.is_builtin_object( argument._proxied ): self.add_message("bad-reversed-sequence", node=node) return if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in argument._proxied.ancestors() ): # Mappings aren't accepted by reversed(), unless # they provide explicitly a __reversed__ method. try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node)
[ "check", "that", "the", "argument", "to", "reversed", "is", "a", "sequence" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1397-L1454
[ "def", "_check_reversed", "(", "self", ",", "node", ")", ":", "try", ":", "argument", "=", "utils", ".", "safe_infer", "(", "utils", ".", "get_argument_from_call", "(", "node", ",", "position", "=", "0", ")", ")", "except", "utils", ".", "NoSuchArgumentError", ":", "pass", "else", ":", "if", "argument", "is", "astroid", ".", "Uninferable", ":", "return", "if", "argument", "is", "None", ":", "# Nothing was infered.", "# Try to see if we have iter().", "if", "isinstance", "(", "node", ".", "args", "[", "0", "]", ",", "astroid", ".", "Call", ")", ":", "try", ":", "func", "=", "next", "(", "node", ".", "args", "[", "0", "]", ".", "func", ".", "infer", "(", ")", ")", "except", "astroid", ".", "InferenceError", ":", "return", "if", "getattr", "(", "func", ",", "\"name\"", ",", "None", ")", "==", "\"iter\"", "and", "utils", ".", "is_builtin_object", "(", "func", ")", ":", "self", ".", "add_message", "(", "\"bad-reversed-sequence\"", ",", "node", "=", "node", ")", "return", "if", "isinstance", "(", "argument", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ")", ")", ":", "return", "if", "isinstance", "(", "argument", ",", "astroid", ".", "Instance", ")", ":", "if", "argument", ".", "_proxied", ".", "name", "==", "\"dict\"", "and", "utils", ".", "is_builtin_object", "(", "argument", ".", "_proxied", ")", ":", "self", ".", "add_message", "(", "\"bad-reversed-sequence\"", ",", "node", "=", "node", ")", "return", "if", "any", "(", "ancestor", ".", "name", "==", "\"dict\"", "and", "utils", ".", "is_builtin_object", "(", "ancestor", ")", "for", "ancestor", "in", "argument", ".", "_proxied", ".", "ancestors", "(", ")", ")", ":", "# Mappings aren't accepted by reversed(), unless", "# they provide explicitly a __reversed__ method.", "try", ":", "argument", ".", "locals", "[", "REVERSED_PROTOCOL_METHOD", "]", "except", "KeyError", ":", "self", ".", "add_message", "(", "\"bad-reversed-sequence\"", ",", "node", "=", "node", ")", "return", "if", "hasattr", "(", "argument", ",", "\"getattr\"", ")", ":", "# everything else is not a proper sequence for reversed()", "for", "methods", "in", "REVERSED_METHODS", ":", "for", "meth", "in", "methods", ":", "try", ":", "argument", ".", "getattr", "(", "meth", ")", "except", "astroid", ".", "NotFoundError", ":", "break", "else", ":", "break", "else", ":", "self", ".", "add_message", "(", "\"bad-reversed-sequence\"", ",", "node", "=", "node", ")", "else", ":", "self", ".", "add_message", "(", "\"bad-reversed-sequence\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
NameChecker.visit_assignname
check module level assigned names
pylint/checkers/base.py
def visit_assignname(self, node): """check module level assigned names""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame() assign_type = node.assign_type() if isinstance(assign_type, astroid.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, astroid.Module): if isinstance(assign_type, astroid.Assign) and not in_loop(assign_type): if isinstance(utils.safe_infer(assign_type.value), astroid.ClassDef): self._check_name("class", node.name, node) else: if not _redefines_import(node): # Don't emit if the name redefines an import # in an ImportError except handler. self._check_name("const", node.name, node) elif isinstance(assign_type, astroid.ExceptHandler): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.ClassDef): if not list(frame.local_attr_ancestors(node.name)): self._check_name("class_attribute", node.name, node)
def visit_assignname(self, node): """check module level assigned names""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame() assign_type = node.assign_type() if isinstance(assign_type, astroid.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, astroid.Module): if isinstance(assign_type, astroid.Assign) and not in_loop(assign_type): if isinstance(utils.safe_infer(assign_type.value), astroid.ClassDef): self._check_name("class", node.name, node) else: if not _redefines_import(node): # Don't emit if the name redefines an import # in an ImportError except handler. self._check_name("const", node.name, node) elif isinstance(assign_type, astroid.ExceptHandler): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.ClassDef): if not list(frame.local_attr_ancestors(node.name)): self._check_name("class_attribute", node.name, node)
[ "check", "module", "level", "assigned", "names" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1759-L1784
[ "def", "visit_assignname", "(", "self", ",", "node", ")", ":", "self", ".", "_check_assign_to_new_keyword_violation", "(", "node", ".", "name", ",", "node", ")", "frame", "=", "node", ".", "frame", "(", ")", "assign_type", "=", "node", ".", "assign_type", "(", ")", "if", "isinstance", "(", "assign_type", ",", "astroid", ".", "Comprehension", ")", ":", "self", ".", "_check_name", "(", "\"inlinevar\"", ",", "node", ".", "name", ",", "node", ")", "elif", "isinstance", "(", "frame", ",", "astroid", ".", "Module", ")", ":", "if", "isinstance", "(", "assign_type", ",", "astroid", ".", "Assign", ")", "and", "not", "in_loop", "(", "assign_type", ")", ":", "if", "isinstance", "(", "utils", ".", "safe_infer", "(", "assign_type", ".", "value", ")", ",", "astroid", ".", "ClassDef", ")", ":", "self", ".", "_check_name", "(", "\"class\"", ",", "node", ".", "name", ",", "node", ")", "else", ":", "if", "not", "_redefines_import", "(", "node", ")", ":", "# Don't emit if the name redefines an import", "# in an ImportError except handler.", "self", ".", "_check_name", "(", "\"const\"", ",", "node", ".", "name", ",", "node", ")", "elif", "isinstance", "(", "assign_type", ",", "astroid", ".", "ExceptHandler", ")", ":", "self", ".", "_check_name", "(", "\"variable\"", ",", "node", ".", "name", ",", "node", ")", "elif", "isinstance", "(", "frame", ",", "astroid", ".", "FunctionDef", ")", ":", "# global introduced variable aren't in the function locals", "if", "node", ".", "name", "in", "frame", "and", "node", ".", "name", "not", "in", "frame", ".", "argnames", "(", ")", ":", "if", "not", "_redefines_import", "(", "node", ")", ":", "self", ".", "_check_name", "(", "\"variable\"", ",", "node", ".", "name", ",", "node", ")", "elif", "isinstance", "(", "frame", ",", "astroid", ".", "ClassDef", ")", ":", "if", "not", "list", "(", "frame", ".", "local_attr_ancestors", "(", "node", ".", "name", ")", ")", ":", "self", ".", "_check_name", "(", "\"class_attribute\"", ",", "node", ".", "name", ",", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
NameChecker._recursive_check_names
check names in a possibly recursive list <arg>
pylint/checkers/base.py
def _recursive_check_names(self, args, node): """check names in a possibly recursive list <arg>""" for arg in args: if isinstance(arg, astroid.AssignName): self._check_name("argument", arg.name, node) else: self._recursive_check_names(arg.elts, node)
def _recursive_check_names(self, args, node): """check names in a possibly recursive list <arg>""" for arg in args: if isinstance(arg, astroid.AssignName): self._check_name("argument", arg.name, node) else: self._recursive_check_names(arg.elts, node)
[ "check", "names", "in", "a", "possibly", "recursive", "list", "<arg", ">" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1786-L1792
[ "def", "_recursive_check_names", "(", "self", ",", "args", ",", "node", ")", ":", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "astroid", ".", "AssignName", ")", ":", "self", ".", "_check_name", "(", "\"argument\"", ",", "arg", ".", "name", ",", "node", ")", "else", ":", "self", ".", "_recursive_check_names", "(", "arg", ".", "elts", ",", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
NameChecker._check_name
check for a name using the type's regexp
pylint/checkers/base.py
def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """check for a name using the type's regexp""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, astroid.ClassDef): return True return False if utils.is_inside_except(node): clobbering, _ = utils.clobber_in_except(node) if clobbering: return if name in self.config.good_names: return if name in self.config.bad_names: self.stats["badname_" + node_type] += 1 self.add_message("blacklisted-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(node, node_type, name, confidence)
def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """check for a name using the type's regexp""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, astroid.ClassDef): return True return False if utils.is_inside_except(node): clobbering, _ = utils.clobber_in_except(node) if clobbering: return if name in self.config.good_names: return if name in self.config.bad_names: self.stats["badname_" + node_type] += 1 self.add_message("blacklisted-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(node, node_type, name, confidence)
[ "check", "for", "a", "name", "using", "the", "type", "s", "regexp" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1807-L1837
[ "def", "_check_name", "(", "self", ",", "node_type", ",", "name", ",", "node", ",", "confidence", "=", "interfaces", ".", "HIGH", ")", ":", "def", "_should_exempt_from_invalid_name", "(", "node", ")", ":", "if", "node_type", "==", "\"variable\"", ":", "inferred", "=", "utils", ".", "safe_infer", "(", "node", ")", "if", "isinstance", "(", "inferred", ",", "astroid", ".", "ClassDef", ")", ":", "return", "True", "return", "False", "if", "utils", ".", "is_inside_except", "(", "node", ")", ":", "clobbering", ",", "_", "=", "utils", ".", "clobber_in_except", "(", "node", ")", "if", "clobbering", ":", "return", "if", "name", "in", "self", ".", "config", ".", "good_names", ":", "return", "if", "name", "in", "self", ".", "config", ".", "bad_names", ":", "self", ".", "stats", "[", "\"badname_\"", "+", "node_type", "]", "+=", "1", "self", ".", "add_message", "(", "\"blacklisted-name\"", ",", "node", "=", "node", ",", "args", "=", "name", ")", "return", "regexp", "=", "self", ".", "_name_regexps", "[", "node_type", "]", "match", "=", "regexp", ".", "match", "(", "name", ")", "if", "_is_multi_naming_match", "(", "match", ",", "node_type", ",", "confidence", ")", ":", "name_group", "=", "self", ".", "_find_name_group", "(", "node_type", ")", "bad_name_group", "=", "self", ".", "_bad_names", ".", "setdefault", "(", "name_group", ",", "{", "}", ")", "warnings", "=", "bad_name_group", ".", "setdefault", "(", "match", ".", "lastgroup", ",", "[", "]", ")", "warnings", ".", "append", "(", "(", "node", ",", "node_type", ",", "name", ",", "confidence", ")", ")", "if", "match", "is", "None", "and", "not", "_should_exempt_from_invalid_name", "(", "node", ")", ":", "self", ".", "_raise_name_warning", "(", "node", ",", "node_type", ",", "name", ",", "confidence", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DocStringChecker._check_docstring
check the node has a non empty docstring
pylint/checkers/base.py
def _check_docstring( self, node_type, node, report_missing=True, confidence=interfaces.HIGH ): """check the node has a non empty docstring""" docstring = node.doc if docstring is None: if not report_missing: return lines = utils.get_node_last_lineno(node) - node.lineno if node_type == "module" and not lines: # If the module has no body, there's no reason # to require a docstring. return max_lines = self.config.docstring_min_length if node_type != "module" and max_lines > -1 and lines < max_lines: return self.stats["undocumented_" + node_type] += 1 if ( node.body and isinstance(node.body[0], astroid.Expr) and isinstance(node.body[0].value, astroid.Call) ): # Most likely a string with a format call. Let's see. func = utils.safe_infer(node.body[0].value.func) if isinstance(func, astroid.BoundMethod) and isinstance( func.bound, astroid.Instance ): # Strings in Python 3, others in Python 2. if PY3K and func.bound.name == "str": return if func.bound.name in ("str", "unicode", "bytes"): return self.add_message( "missing-docstring", node=node, args=(node_type,), confidence=confidence ) elif not docstring.strip(): self.stats["undocumented_" + node_type] += 1 self.add_message( "empty-docstring", node=node, args=(node_type,), confidence=confidence )
def _check_docstring( self, node_type, node, report_missing=True, confidence=interfaces.HIGH ): """check the node has a non empty docstring""" docstring = node.doc if docstring is None: if not report_missing: return lines = utils.get_node_last_lineno(node) - node.lineno if node_type == "module" and not lines: # If the module has no body, there's no reason # to require a docstring. return max_lines = self.config.docstring_min_length if node_type != "module" and max_lines > -1 and lines < max_lines: return self.stats["undocumented_" + node_type] += 1 if ( node.body and isinstance(node.body[0], astroid.Expr) and isinstance(node.body[0].value, astroid.Call) ): # Most likely a string with a format call. Let's see. func = utils.safe_infer(node.body[0].value.func) if isinstance(func, astroid.BoundMethod) and isinstance( func.bound, astroid.Instance ): # Strings in Python 3, others in Python 2. if PY3K and func.bound.name == "str": return if func.bound.name in ("str", "unicode", "bytes"): return self.add_message( "missing-docstring", node=node, args=(node_type,), confidence=confidence ) elif not docstring.strip(): self.stats["undocumented_" + node_type] += 1 self.add_message( "empty-docstring", node=node, args=(node_type,), confidence=confidence )
[ "check", "the", "node", "has", "a", "non", "empty", "docstring" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L1957-L1998
[ "def", "_check_docstring", "(", "self", ",", "node_type", ",", "node", ",", "report_missing", "=", "True", ",", "confidence", "=", "interfaces", ".", "HIGH", ")", ":", "docstring", "=", "node", ".", "doc", "if", "docstring", "is", "None", ":", "if", "not", "report_missing", ":", "return", "lines", "=", "utils", ".", "get_node_last_lineno", "(", "node", ")", "-", "node", ".", "lineno", "if", "node_type", "==", "\"module\"", "and", "not", "lines", ":", "# If the module has no body, there's no reason", "# to require a docstring.", "return", "max_lines", "=", "self", ".", "config", ".", "docstring_min_length", "if", "node_type", "!=", "\"module\"", "and", "max_lines", ">", "-", "1", "and", "lines", "<", "max_lines", ":", "return", "self", ".", "stats", "[", "\"undocumented_\"", "+", "node_type", "]", "+=", "1", "if", "(", "node", ".", "body", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ",", "astroid", ".", "Expr", ")", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ".", "value", ",", "astroid", ".", "Call", ")", ")", ":", "# Most likely a string with a format call. Let's see.", "func", "=", "utils", ".", "safe_infer", "(", "node", ".", "body", "[", "0", "]", ".", "value", ".", "func", ")", "if", "isinstance", "(", "func", ",", "astroid", ".", "BoundMethod", ")", "and", "isinstance", "(", "func", ".", "bound", ",", "astroid", ".", "Instance", ")", ":", "# Strings in Python 3, others in Python 2.", "if", "PY3K", "and", "func", ".", "bound", ".", "name", "==", "\"str\"", ":", "return", "if", "func", ".", "bound", ".", "name", "in", "(", "\"str\"", ",", "\"unicode\"", ",", "\"bytes\"", ")", ":", "return", "self", ".", "add_message", "(", "\"missing-docstring\"", ",", "node", "=", "node", ",", "args", "=", "(", "node_type", ",", ")", ",", "confidence", "=", "confidence", ")", "elif", "not", "docstring", ".", "strip", "(", ")", ":", "self", ".", "stats", "[", "\"undocumented_\"", "+", "node_type", "]", "+=", "1", "self", ".", "add_message", "(", "\"empty-docstring\"", ",", "node", "=", "node", ",", "args", "=", "(", "node_type", ",", ")", ",", "confidence", "=", "confidence", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ComparisonChecker._check_literal_comparison
Check if we compare to a literal, which is usually what we do not want to do.
pylint/checkers/base.py
def _check_literal_comparison(self, literal, node): """Check if we compare to a literal, which is usually what we do not want to do.""" nodes = (astroid.List, astroid.Tuple, astroid.Dict, astroid.Set) is_other_literal = isinstance(literal, nodes) is_const = False if isinstance(literal, astroid.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in this values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node)
def _check_literal_comparison(self, literal, node): """Check if we compare to a literal, which is usually what we do not want to do.""" nodes = (astroid.List, astroid.Tuple, astroid.Dict, astroid.Set) is_other_literal = isinstance(literal, nodes) is_const = False if isinstance(literal, astroid.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in this values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node)
[ "Check", "if", "we", "compare", "to", "a", "literal", "which", "is", "usually", "what", "we", "do", "not", "want", "to", "do", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L2107-L2119
[ "def", "_check_literal_comparison", "(", "self", ",", "literal", ",", "node", ")", ":", "nodes", "=", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ",", "astroid", ".", "Dict", ",", "astroid", ".", "Set", ")", "is_other_literal", "=", "isinstance", "(", "literal", ",", "nodes", ")", "is_const", "=", "False", "if", "isinstance", "(", "literal", ",", "astroid", ".", "Const", ")", ":", "if", "isinstance", "(", "literal", ".", "value", ",", "bool", ")", "or", "literal", ".", "value", "is", "None", ":", "# Not interested in this values.", "return", "is_const", "=", "isinstance", "(", "literal", ".", "value", ",", "(", "bytes", ",", "str", ",", "int", ",", "float", ")", ")", "if", "is_const", "or", "is_other_literal", ":", "self", ".", "add_message", "(", "\"literal-comparison\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ComparisonChecker._check_logical_tautology
Check if identifier is compared against itself. :param node: Compare node :type node: astroid.node_classes.Compare :Example: val = 786 if val == val: # [comparison-with-itself] pass
pylint/checkers/base.py
def _check_logical_tautology(self, node): """Check if identifier is compared against itself. :param node: Compare node :type node: astroid.node_classes.Compare :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, astroid.Const) and isinstance( right_operand, astroid.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, astroid.Name) and isinstance( right_operand, astroid.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = "%s %s %s" % (left_operand, operator, right_operand) self.add_message("comparison-with-itself", node=node, args=(suggestion,))
def _check_logical_tautology(self, node): """Check if identifier is compared against itself. :param node: Compare node :type node: astroid.node_classes.Compare :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, astroid.Const) and isinstance( right_operand, astroid.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, astroid.Name) and isinstance( right_operand, astroid.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = "%s %s %s" % (left_operand, operator, right_operand) self.add_message("comparison-with-itself", node=node, args=(suggestion,))
[ "Check", "if", "identifier", "is", "compared", "against", "itself", ".", ":", "param", "node", ":", "Compare", "node", ":", "type", "node", ":", "astroid", ".", "node_classes", ".", "Compare", ":", "Example", ":", "val", "=", "786", "if", "val", "==", "val", ":", "#", "[", "comparison", "-", "with", "-", "itself", "]", "pass" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L2128-L2153
[ "def", "_check_logical_tautology", "(", "self", ",", "node", ")", ":", "left_operand", "=", "node", ".", "left", "right_operand", "=", "node", ".", "ops", "[", "0", "]", "[", "1", "]", "operator", "=", "node", ".", "ops", "[", "0", "]", "[", "0", "]", "if", "isinstance", "(", "left_operand", ",", "astroid", ".", "Const", ")", "and", "isinstance", "(", "right_operand", ",", "astroid", ".", "Const", ")", ":", "left_operand", "=", "left_operand", ".", "value", "right_operand", "=", "right_operand", ".", "value", "elif", "isinstance", "(", "left_operand", ",", "astroid", ".", "Name", ")", "and", "isinstance", "(", "right_operand", ",", "astroid", ".", "Name", ")", ":", "left_operand", "=", "left_operand", ".", "name", "right_operand", "=", "right_operand", ".", "name", "if", "left_operand", "==", "right_operand", ":", "suggestion", "=", "\"%s %s %s\"", "%", "(", "left_operand", ",", "operator", ",", "right_operand", ")", "self", ".", "add_message", "(", "\"comparison-with-itself\"", ",", "node", "=", "node", ",", "args", "=", "(", "suggestion", ",", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ComparisonChecker._check_type_x_is_y
Check for expressions like type(x) == Y.
pylint/checkers/base.py
def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, astroid.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in ("is", "is not") and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, astroid.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, astroid.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in ("is", "is not") and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, astroid.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
[ "Check", "for", "expressions", "like", "type", "(", "x", ")", "==", "Y", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L2214-L2233
[ "def", "_check_type_x_is_y", "(", "self", ",", "node", ",", "left", ",", "operator", ",", "right", ")", ":", "left_func", "=", "utils", ".", "safe_infer", "(", "left", ".", "func", ")", "if", "not", "(", "isinstance", "(", "left_func", ",", "astroid", ".", "ClassDef", ")", "and", "left_func", ".", "qname", "(", ")", "==", "TYPE_QNAME", ")", ":", "return", "if", "operator", "in", "(", "\"is\"", ",", "\"is not\"", ")", "and", "_is_one_arg_pos_call", "(", "right", ")", ":", "right_func", "=", "utils", ".", "safe_infer", "(", "right", ".", "func", ")", "if", "(", "isinstance", "(", "right_func", ",", "astroid", ".", "ClassDef", ")", "and", "right_func", ".", "qname", "(", ")", "==", "TYPE_QNAME", ")", ":", "# type(x) == type(a)", "right_arg", "=", "utils", ".", "safe_infer", "(", "right", ".", "args", "[", "0", "]", ")", "if", "not", "isinstance", "(", "right_arg", ",", "LITERAL_NODE_TYPES", ")", ":", "# not e.g. type(x) == type([])", "return", "self", ".", "add_message", "(", "\"unidiomatic-typecheck\"", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PathGraphingAstVisitor._subgraph
create the subgraphs representing any `if` and `for` statements
pylint/extensions/mccabe.py
def _subgraph(self, node, name, extra_blocks=()): """create the subgraphs representing any `if` and `for` statements""" if self.graph is None: # global loop self.graph = PathGraph(node) self._subgraph_parse(node, node, extra_blocks) self.graphs["%s%s" % (self.classname, name)] = self.graph self.reset() else: self._append_node(node) self._subgraph_parse(node, node, extra_blocks)
def _subgraph(self, node, name, extra_blocks=()): """create the subgraphs representing any `if` and `for` statements""" if self.graph is None: # global loop self.graph = PathGraph(node) self._subgraph_parse(node, node, extra_blocks) self.graphs["%s%s" % (self.classname, name)] = self.graph self.reset() else: self._append_node(node) self._subgraph_parse(node, node, extra_blocks)
[ "create", "the", "subgraphs", "representing", "any", "if", "and", "for", "statements" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/mccabe.py#L107-L117
[ "def", "_subgraph", "(", "self", ",", "node", ",", "name", ",", "extra_blocks", "=", "(", ")", ")", ":", "if", "self", ".", "graph", "is", "None", ":", "# global loop", "self", ".", "graph", "=", "PathGraph", "(", "node", ")", "self", ".", "_subgraph_parse", "(", "node", ",", "node", ",", "extra_blocks", ")", "self", ".", "graphs", "[", "\"%s%s\"", "%", "(", "self", ".", "classname", ",", "name", ")", "]", "=", "self", ".", "graph", "self", ".", "reset", "(", ")", "else", ":", "self", ".", "_append_node", "(", "node", ")", "self", ".", "_subgraph_parse", "(", "node", ",", "node", ",", "extra_blocks", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PathGraphingAstVisitor._subgraph_parse
parse the body and any `else` block of `if` and `for` statements
pylint/extensions/mccabe.py
def _subgraph_parse( self, node, pathnode, extra_blocks ): # pylint: disable=unused-argument """parse the body and any `else` block of `if` and `for` statements""" loose_ends = [] self.tail = node self.dispatch_list(node.body) loose_ends.append(self.tail) for extra in extra_blocks: self.tail = node self.dispatch_list(extra.body) loose_ends.append(self.tail) if node.orelse: self.tail = node self.dispatch_list(node.orelse) loose_ends.append(self.tail) else: loose_ends.append(node) if node: bottom = "%s" % self._bottom_counter self._bottom_counter += 1 for le in loose_ends: self.graph.connect(le, bottom) self.tail = bottom
def _subgraph_parse( self, node, pathnode, extra_blocks ): # pylint: disable=unused-argument """parse the body and any `else` block of `if` and `for` statements""" loose_ends = [] self.tail = node self.dispatch_list(node.body) loose_ends.append(self.tail) for extra in extra_blocks: self.tail = node self.dispatch_list(extra.body) loose_ends.append(self.tail) if node.orelse: self.tail = node self.dispatch_list(node.orelse) loose_ends.append(self.tail) else: loose_ends.append(node) if node: bottom = "%s" % self._bottom_counter self._bottom_counter += 1 for le in loose_ends: self.graph.connect(le, bottom) self.tail = bottom
[ "parse", "the", "body", "and", "any", "else", "block", "of", "if", "and", "for", "statements" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/mccabe.py#L119-L142
[ "def", "_subgraph_parse", "(", "self", ",", "node", ",", "pathnode", ",", "extra_blocks", ")", ":", "# pylint: disable=unused-argument", "loose_ends", "=", "[", "]", "self", ".", "tail", "=", "node", "self", ".", "dispatch_list", "(", "node", ".", "body", ")", "loose_ends", ".", "append", "(", "self", ".", "tail", ")", "for", "extra", "in", "extra_blocks", ":", "self", ".", "tail", "=", "node", "self", ".", "dispatch_list", "(", "extra", ".", "body", ")", "loose_ends", ".", "append", "(", "self", ".", "tail", ")", "if", "node", ".", "orelse", ":", "self", ".", "tail", "=", "node", "self", ".", "dispatch_list", "(", "node", ".", "orelse", ")", "loose_ends", ".", "append", "(", "self", ".", "tail", ")", "else", ":", "loose_ends", ".", "append", "(", "node", ")", "if", "node", ":", "bottom", "=", "\"%s\"", "%", "self", ".", "_bottom_counter", "self", ".", "_bottom_counter", "+=", "1", "for", "le", "in", "loose_ends", ":", "self", ".", "graph", ".", "connect", "(", "le", ",", "bottom", ")", "self", ".", "tail", "=", "bottom" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
McCabeMethodChecker.visit_module
visit an astroid.Module node to check too complex rating and add message if is greather than max_complexity stored from options
pylint/extensions/mccabe.py
def visit_module(self, node): """visit an astroid.Module node to check too complex rating and add message if is greather than max_complexity stored from options""" visitor = PathGraphingAstVisitor() for child in node.body: visitor.preorder(child, visitor) for graph in visitor.graphs.values(): complexity = graph.complexity() node = graph.root if hasattr(node, "name"): node_name = "'%s'" % node.name else: node_name = "This '%s'" % node.__class__.__name__.lower() if complexity <= self.config.max_complexity: continue self.add_message( "too-complex", node=node, confidence=HIGH, args=(node_name, complexity) )
def visit_module(self, node): """visit an astroid.Module node to check too complex rating and add message if is greather than max_complexity stored from options""" visitor = PathGraphingAstVisitor() for child in node.body: visitor.preorder(child, visitor) for graph in visitor.graphs.values(): complexity = graph.complexity() node = graph.root if hasattr(node, "name"): node_name = "'%s'" % node.name else: node_name = "This '%s'" % node.__class__.__name__.lower() if complexity <= self.config.max_complexity: continue self.add_message( "too-complex", node=node, confidence=HIGH, args=(node_name, complexity) )
[ "visit", "an", "astroid", ".", "Module", "node", "to", "check", "too", "complex", "rating", "and", "add", "message", "if", "is", "greather", "than", "max_complexity", "stored", "from", "options" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/mccabe.py#L174-L191
[ "def", "visit_module", "(", "self", ",", "node", ")", ":", "visitor", "=", "PathGraphingAstVisitor", "(", ")", "for", "child", "in", "node", ".", "body", ":", "visitor", ".", "preorder", "(", "child", ",", "visitor", ")", "for", "graph", "in", "visitor", ".", "graphs", ".", "values", "(", ")", ":", "complexity", "=", "graph", ".", "complexity", "(", ")", "node", "=", "graph", ".", "root", "if", "hasattr", "(", "node", ",", "\"name\"", ")", ":", "node_name", "=", "\"'%s'\"", "%", "node", ".", "name", "else", ":", "node_name", "=", "\"This '%s'\"", "%", "node", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "if", "complexity", "<=", "self", ".", "config", ".", "max_complexity", ":", "continue", "self", ".", "add_message", "(", "\"too-complex\"", ",", "node", "=", "node", ",", "confidence", "=", "HIGH", ",", "args", "=", "(", "node_name", ",", "complexity", ")", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ASTWalker.add_checker
walk to the checker's dir and collect visit and leave methods
pylint/utils/ast_walker.py
def add_checker(self, checker): """walk to the checker's dir and collect visit and leave methods""" # XXX : should be possible to merge needed_checkers and add_checker vcids = set() lcids = set() visits = self.visit_events leaves = self.leave_events for member in dir(checker): cid = member[6:] if cid == "default": continue if member.startswith("visit_"): v_meth = getattr(checker, member) # don't use visit_methods with no activated message: if self._is_method_enabled(v_meth): visits[cid].append(v_meth) vcids.add(cid) elif member.startswith("leave_"): l_meth = getattr(checker, member) # don't use leave_methods with no activated message: if self._is_method_enabled(l_meth): leaves[cid].append(l_meth) lcids.add(cid) visit_default = getattr(checker, "visit_default", None) if visit_default: for cls in nodes.ALL_NODE_CLASSES: cid = cls.__name__.lower() if cid not in vcids: visits[cid].append(visit_default)
def add_checker(self, checker): """walk to the checker's dir and collect visit and leave methods""" # XXX : should be possible to merge needed_checkers and add_checker vcids = set() lcids = set() visits = self.visit_events leaves = self.leave_events for member in dir(checker): cid = member[6:] if cid == "default": continue if member.startswith("visit_"): v_meth = getattr(checker, member) # don't use visit_methods with no activated message: if self._is_method_enabled(v_meth): visits[cid].append(v_meth) vcids.add(cid) elif member.startswith("leave_"): l_meth = getattr(checker, member) # don't use leave_methods with no activated message: if self._is_method_enabled(l_meth): leaves[cid].append(l_meth) lcids.add(cid) visit_default = getattr(checker, "visit_default", None) if visit_default: for cls in nodes.ALL_NODE_CLASSES: cid = cls.__name__.lower() if cid not in vcids: visits[cid].append(visit_default)
[ "walk", "to", "the", "checker", "s", "dir", "and", "collect", "visit", "and", "leave", "methods" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/ast_walker.py#L27-L55
[ "def", "add_checker", "(", "self", ",", "checker", ")", ":", "# XXX : should be possible to merge needed_checkers and add_checker", "vcids", "=", "set", "(", ")", "lcids", "=", "set", "(", ")", "visits", "=", "self", ".", "visit_events", "leaves", "=", "self", ".", "leave_events", "for", "member", "in", "dir", "(", "checker", ")", ":", "cid", "=", "member", "[", "6", ":", "]", "if", "cid", "==", "\"default\"", ":", "continue", "if", "member", ".", "startswith", "(", "\"visit_\"", ")", ":", "v_meth", "=", "getattr", "(", "checker", ",", "member", ")", "# don't use visit_methods with no activated message:", "if", "self", ".", "_is_method_enabled", "(", "v_meth", ")", ":", "visits", "[", "cid", "]", ".", "append", "(", "v_meth", ")", "vcids", ".", "add", "(", "cid", ")", "elif", "member", ".", "startswith", "(", "\"leave_\"", ")", ":", "l_meth", "=", "getattr", "(", "checker", ",", "member", ")", "# don't use leave_methods with no activated message:", "if", "self", ".", "_is_method_enabled", "(", "l_meth", ")", ":", "leaves", "[", "cid", "]", ".", "append", "(", "l_meth", ")", "lcids", ".", "add", "(", "cid", ")", "visit_default", "=", "getattr", "(", "checker", ",", "\"visit_default\"", ",", "None", ")", "if", "visit_default", ":", "for", "cls", "in", "nodes", ".", "ALL_NODE_CLASSES", ":", "cid", "=", "cls", ".", "__name__", ".", "lower", "(", ")", "if", "cid", "not", "in", "vcids", ":", "visits", "[", "cid", "]", ".", "append", "(", "visit_default", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ASTWalker.walk
call visit events of astroid checkers for the given node, recurse on its children, then leave events.
pylint/utils/ast_walker.py
def walk(self, astroid): """call visit events of astroid checkers for the given node, recurse on its children, then leave events. """ cid = astroid.__class__.__name__.lower() # Detect if the node is a new name for a deprecated alias. # In this case, favour the methods for the deprecated # alias if any, in order to maintain backwards # compatibility. visit_events = self.visit_events.get(cid, ()) leave_events = self.leave_events.get(cid, ()) if astroid.is_statement: self.nbstatements += 1 # generate events for this node on each checker for cb in visit_events or (): cb(astroid) # recurse on children for child in astroid.get_children(): self.walk(child) for cb in leave_events or (): cb(astroid)
def walk(self, astroid): """call visit events of astroid checkers for the given node, recurse on its children, then leave events. """ cid = astroid.__class__.__name__.lower() # Detect if the node is a new name for a deprecated alias. # In this case, favour the methods for the deprecated # alias if any, in order to maintain backwards # compatibility. visit_events = self.visit_events.get(cid, ()) leave_events = self.leave_events.get(cid, ()) if astroid.is_statement: self.nbstatements += 1 # generate events for this node on each checker for cb in visit_events or (): cb(astroid) # recurse on children for child in astroid.get_children(): self.walk(child) for cb in leave_events or (): cb(astroid)
[ "call", "visit", "events", "of", "astroid", "checkers", "for", "the", "given", "node", "recurse", "on", "its", "children", "then", "leave", "events", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/ast_walker.py#L58-L80
[ "def", "walk", "(", "self", ",", "astroid", ")", ":", "cid", "=", "astroid", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "# Detect if the node is a new name for a deprecated alias.", "# In this case, favour the methods for the deprecated", "# alias if any, in order to maintain backwards", "# compatibility.", "visit_events", "=", "self", ".", "visit_events", ".", "get", "(", "cid", ",", "(", ")", ")", "leave_events", "=", "self", ".", "leave_events", ".", "get", "(", "cid", ",", "(", ")", ")", "if", "astroid", ".", "is_statement", ":", "self", ".", "nbstatements", "+=", "1", "# generate events for this node on each checker", "for", "cb", "in", "visit_events", "or", "(", ")", ":", "cb", "(", "astroid", ")", "# recurse on children", "for", "child", "in", "astroid", ".", "get_children", "(", ")", ":", "self", ".", "walk", "(", "child", ")", "for", "cb", "in", "leave_events", "or", "(", ")", ":", "cb", "(", "astroid", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.add_relationship
create a relation ship
pylint/pyreverse/diagrams.py
def add_relationship(self, from_object, to_object, relation_type, name=None): """create a relation ship """ rel = Relationship(from_object, to_object, relation_type, name) self.relationships.setdefault(relation_type, []).append(rel)
def add_relationship(self, from_object, to_object, relation_type, name=None): """create a relation ship """ rel = Relationship(from_object, to_object, relation_type, name) self.relationships.setdefault(relation_type, []).append(rel)
[ "create", "a", "relation", "ship" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L68-L72
[ "def", "add_relationship", "(", "self", ",", "from_object", ",", "to_object", ",", "relation_type", ",", "name", "=", "None", ")", ":", "rel", "=", "Relationship", "(", "from_object", ",", "to_object", ",", "relation_type", ",", "name", ")", "self", ".", "relationships", ".", "setdefault", "(", "relation_type", ",", "[", "]", ")", ".", "append", "(", "rel", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.get_relationship
return a relation ship or None
pylint/pyreverse/diagrams.py
def get_relationship(self, from_object, relation_type): """return a relation ship or None """ for rel in self.relationships.get(relation_type, ()): if rel.from_object is from_object: return rel raise KeyError(relation_type)
def get_relationship(self, from_object, relation_type): """return a relation ship or None """ for rel in self.relationships.get(relation_type, ()): if rel.from_object is from_object: return rel raise KeyError(relation_type)
[ "return", "a", "relation", "ship", "or", "None" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L74-L80
[ "def", "get_relationship", "(", "self", ",", "from_object", ",", "relation_type", ")", ":", "for", "rel", "in", "self", ".", "relationships", ".", "get", "(", "relation_type", ",", "(", ")", ")", ":", "if", "rel", ".", "from_object", "is", "from_object", ":", "return", "rel", "raise", "KeyError", "(", "relation_type", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.get_attrs
return visible attributes, possibly with class name
pylint/pyreverse/diagrams.py
def get_attrs(self, node): """return visible attributes, possibly with class name""" attrs = [] properties = [ (n, m) for n, m in node.items() if isinstance(m, astroid.FunctionDef) and decorated_with_property(m) ] for node_name, associated_nodes in ( list(node.instance_attrs_type.items()) + list(node.locals_type.items()) + properties ): if not self.show_attr(node_name): continue names = self.class_names(associated_nodes) if names: node_name = "%s : %s" % (node_name, ", ".join(names)) attrs.append(node_name) return sorted(attrs)
def get_attrs(self, node): """return visible attributes, possibly with class name""" attrs = [] properties = [ (n, m) for n, m in node.items() if isinstance(m, astroid.FunctionDef) and decorated_with_property(m) ] for node_name, associated_nodes in ( list(node.instance_attrs_type.items()) + list(node.locals_type.items()) + properties ): if not self.show_attr(node_name): continue names = self.class_names(associated_nodes) if names: node_name = "%s : %s" % (node_name, ", ".join(names)) attrs.append(node_name) return sorted(attrs)
[ "return", "visible", "attributes", "possibly", "with", "class", "name" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L82-L101
[ "def", "get_attrs", "(", "self", ",", "node", ")", ":", "attrs", "=", "[", "]", "properties", "=", "[", "(", "n", ",", "m", ")", "for", "n", ",", "m", "in", "node", ".", "items", "(", ")", "if", "isinstance", "(", "m", ",", "astroid", ".", "FunctionDef", ")", "and", "decorated_with_property", "(", "m", ")", "]", "for", "node_name", ",", "associated_nodes", "in", "(", "list", "(", "node", ".", "instance_attrs_type", ".", "items", "(", ")", ")", "+", "list", "(", "node", ".", "locals_type", ".", "items", "(", ")", ")", "+", "properties", ")", ":", "if", "not", "self", ".", "show_attr", "(", "node_name", ")", ":", "continue", "names", "=", "self", ".", "class_names", "(", "associated_nodes", ")", "if", "names", ":", "node_name", "=", "\"%s : %s\"", "%", "(", "node_name", ",", "\", \"", ".", "join", "(", "names", ")", ")", "attrs", ".", "append", "(", "node_name", ")", "return", "sorted", "(", "attrs", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.get_methods
return visible methods
pylint/pyreverse/diagrams.py
def get_methods(self, node): """return visible methods""" methods = [ m for m in node.values() if isinstance(m, astroid.FunctionDef) and not decorated_with_property(m) and self.show_attr(m.name) ] return sorted(methods, key=lambda n: n.name)
def get_methods(self, node): """return visible methods""" methods = [ m for m in node.values() if isinstance(m, astroid.FunctionDef) and not decorated_with_property(m) and self.show_attr(m.name) ] return sorted(methods, key=lambda n: n.name)
[ "return", "visible", "methods" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L103-L112
[ "def", "get_methods", "(", "self", ",", "node", ")", ":", "methods", "=", "[", "m", "for", "m", "in", "node", ".", "values", "(", ")", "if", "isinstance", "(", "m", ",", "astroid", ".", "FunctionDef", ")", "and", "not", "decorated_with_property", "(", "m", ")", "and", "self", ".", "show_attr", "(", "m", ".", "name", ")", "]", "return", "sorted", "(", "methods", ",", "key", "=", "lambda", "n", ":", "n", ".", "name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.add_object
create a diagram object
pylint/pyreverse/diagrams.py
def add_object(self, title, node): """create a diagram object """ assert node not in self._nodes ent = DiagramEntity(title, node) self._nodes[node] = ent self.objects.append(ent)
def add_object(self, title, node): """create a diagram object """ assert node not in self._nodes ent = DiagramEntity(title, node) self._nodes[node] = ent self.objects.append(ent)
[ "create", "a", "diagram", "object" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L114-L120
[ "def", "add_object", "(", "self", ",", "title", ",", "node", ")", ":", "assert", "node", "not", "in", "self", ".", "_nodes", "ent", "=", "DiagramEntity", "(", "title", ",", "node", ")", "self", ".", "_nodes", "[", "node", "]", "=", "ent", "self", ".", "objects", ".", "append", "(", "ent", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.class_names
return class names if needed in diagram
pylint/pyreverse/diagrams.py
def class_names(self, nodes): """return class names if needed in diagram""" names = [] for node in nodes: if isinstance(node, astroid.Instance): node = node._proxied if ( isinstance(node, astroid.ClassDef) and hasattr(node, "name") and not self.has_node(node) ): if node.name not in names: node_name = node.name names.append(node_name) return names
def class_names(self, nodes): """return class names if needed in diagram""" names = [] for node in nodes: if isinstance(node, astroid.Instance): node = node._proxied if ( isinstance(node, astroid.ClassDef) and hasattr(node, "name") and not self.has_node(node) ): if node.name not in names: node_name = node.name names.append(node_name) return names
[ "return", "class", "names", "if", "needed", "in", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L122-L136
[ "def", "class_names", "(", "self", ",", "nodes", ")", ":", "names", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "isinstance", "(", "node", ",", "astroid", ".", "Instance", ")", ":", "node", "=", "node", ".", "_proxied", "if", "(", "isinstance", "(", "node", ",", "astroid", ".", "ClassDef", ")", "and", "hasattr", "(", "node", ",", "\"name\"", ")", "and", "not", "self", ".", "has_node", "(", "node", ")", ")", ":", "if", "node", ".", "name", "not", "in", "names", ":", "node_name", "=", "node", ".", "name", "names", ".", "append", "(", "node_name", ")", "return", "names" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.classes
return all class nodes in the diagram
pylint/pyreverse/diagrams.py
def classes(self): """return all class nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)]
def classes(self): """return all class nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)]
[ "return", "all", "class", "nodes", "in", "the", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L153-L155
[ "def", "classes", "(", "self", ")", ":", "return", "[", "o", "for", "o", "in", "self", ".", "objects", "if", "isinstance", "(", "o", ".", "node", ",", "astroid", ".", "ClassDef", ")", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.classe
return a class by its name, raise KeyError if not found
pylint/pyreverse/diagrams.py
def classe(self, name): """return a class by its name, raise KeyError if not found """ for klass in self.classes(): if klass.node.name == name: return klass raise KeyError(name)
def classe(self, name): """return a class by its name, raise KeyError if not found """ for klass in self.classes(): if klass.node.name == name: return klass raise KeyError(name)
[ "return", "a", "class", "by", "its", "name", "raise", "KeyError", "if", "not", "found" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L157-L163
[ "def", "classe", "(", "self", ",", "name", ")", ":", "for", "klass", "in", "self", ".", "classes", "(", ")", ":", "if", "klass", ".", "node", ".", "name", "==", "name", ":", "return", "klass", "raise", "KeyError", "(", "name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
ClassDiagram.extract_relationships
extract relation ships between nodes in the diagram
pylint/pyreverse/diagrams.py
def extract_relationships(self): """extract relation ships between nodes in the diagram """ for obj in self.classes(): node = obj.node obj.attrs = self.get_attrs(node) obj.methods = self.get_methods(node) # shape if is_interface(node): obj.shape = "interface" else: obj.shape = "class" # inheritance link for par_node in node.ancestors(recurs=False): try: par_obj = self.object_from_node(par_node) self.add_relationship(obj, par_obj, "specialization") except KeyError: continue # implements link for impl_node in node.implements: try: impl_obj = self.object_from_node(impl_node) self.add_relationship(obj, impl_obj, "implements") except KeyError: continue # associations link for name, values in list(node.instance_attrs_type.items()) + list( node.locals_type.items() ): for value in values: if value is astroid.Uninferable: continue if isinstance(value, astroid.Instance): value = value._proxied try: associated_obj = self.object_from_node(value) self.add_relationship(associated_obj, obj, "association", name) except KeyError: continue
def extract_relationships(self): """extract relation ships between nodes in the diagram """ for obj in self.classes(): node = obj.node obj.attrs = self.get_attrs(node) obj.methods = self.get_methods(node) # shape if is_interface(node): obj.shape = "interface" else: obj.shape = "class" # inheritance link for par_node in node.ancestors(recurs=False): try: par_obj = self.object_from_node(par_node) self.add_relationship(obj, par_obj, "specialization") except KeyError: continue # implements link for impl_node in node.implements: try: impl_obj = self.object_from_node(impl_node) self.add_relationship(obj, impl_obj, "implements") except KeyError: continue # associations link for name, values in list(node.instance_attrs_type.items()) + list( node.locals_type.items() ): for value in values: if value is astroid.Uninferable: continue if isinstance(value, astroid.Instance): value = value._proxied try: associated_obj = self.object_from_node(value) self.add_relationship(associated_obj, obj, "association", name) except KeyError: continue
[ "extract", "relation", "ships", "between", "nodes", "in", "the", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L165-L204
[ "def", "extract_relationships", "(", "self", ")", ":", "for", "obj", "in", "self", ".", "classes", "(", ")", ":", "node", "=", "obj", ".", "node", "obj", ".", "attrs", "=", "self", ".", "get_attrs", "(", "node", ")", "obj", ".", "methods", "=", "self", ".", "get_methods", "(", "node", ")", "# shape", "if", "is_interface", "(", "node", ")", ":", "obj", ".", "shape", "=", "\"interface\"", "else", ":", "obj", ".", "shape", "=", "\"class\"", "# inheritance link", "for", "par_node", "in", "node", ".", "ancestors", "(", "recurs", "=", "False", ")", ":", "try", ":", "par_obj", "=", "self", ".", "object_from_node", "(", "par_node", ")", "self", ".", "add_relationship", "(", "obj", ",", "par_obj", ",", "\"specialization\"", ")", "except", "KeyError", ":", "continue", "# implements link", "for", "impl_node", "in", "node", ".", "implements", ":", "try", ":", "impl_obj", "=", "self", ".", "object_from_node", "(", "impl_node", ")", "self", ".", "add_relationship", "(", "obj", ",", "impl_obj", ",", "\"implements\"", ")", "except", "KeyError", ":", "continue", "# associations link", "for", "name", ",", "values", "in", "list", "(", "node", ".", "instance_attrs_type", ".", "items", "(", ")", ")", "+", "list", "(", "node", ".", "locals_type", ".", "items", "(", ")", ")", ":", "for", "value", "in", "values", ":", "if", "value", "is", "astroid", ".", "Uninferable", ":", "continue", "if", "isinstance", "(", "value", ",", "astroid", ".", "Instance", ")", ":", "value", "=", "value", ".", "_proxied", "try", ":", "associated_obj", "=", "self", ".", "object_from_node", "(", "value", ")", "self", ".", "add_relationship", "(", "associated_obj", ",", "obj", ",", "\"association\"", ",", "name", ")", "except", "KeyError", ":", "continue" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PackageDiagram.modules
return all module nodes in the diagram
pylint/pyreverse/diagrams.py
def modules(self): """return all module nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.Module)]
def modules(self): """return all module nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.Module)]
[ "return", "all", "module", "nodes", "in", "the", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L213-L215
[ "def", "modules", "(", "self", ")", ":", "return", "[", "o", "for", "o", "in", "self", ".", "objects", "if", "isinstance", "(", "o", ".", "node", ",", "astroid", ".", "Module", ")", "]" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PackageDiagram.module
return a module by its name, raise KeyError if not found
pylint/pyreverse/diagrams.py
def module(self, name): """return a module by its name, raise KeyError if not found """ for mod in self.modules(): if mod.node.name == name: return mod raise KeyError(name)
def module(self, name): """return a module by its name, raise KeyError if not found """ for mod in self.modules(): if mod.node.name == name: return mod raise KeyError(name)
[ "return", "a", "module", "by", "its", "name", "raise", "KeyError", "if", "not", "found" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L217-L223
[ "def", "module", "(", "self", ",", "name", ")", ":", "for", "mod", "in", "self", ".", "modules", "(", ")", ":", "if", "mod", ".", "node", ".", "name", "==", "name", ":", "return", "mod", "raise", "KeyError", "(", "name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PackageDiagram.get_module
return a module by its name, looking also for relative imports; raise KeyError if not found
pylint/pyreverse/diagrams.py
def get_module(self, name, node): """return a module by its name, looking also for relative imports; raise KeyError if not found """ for mod in self.modules(): mod_name = mod.node.name if mod_name == name: return mod # search for fullname of relative import modules package = node.root().name if mod_name == "%s.%s" % (package, name): return mod if mod_name == "%s.%s" % (package.rsplit(".", 1)[0], name): return mod raise KeyError(name)
def get_module(self, name, node): """return a module by its name, looking also for relative imports; raise KeyError if not found """ for mod in self.modules(): mod_name = mod.node.name if mod_name == name: return mod # search for fullname of relative import modules package = node.root().name if mod_name == "%s.%s" % (package, name): return mod if mod_name == "%s.%s" % (package.rsplit(".", 1)[0], name): return mod raise KeyError(name)
[ "return", "a", "module", "by", "its", "name", "looking", "also", "for", "relative", "imports", ";", "raise", "KeyError", "if", "not", "found" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L225-L239
[ "def", "get_module", "(", "self", ",", "name", ",", "node", ")", ":", "for", "mod", "in", "self", ".", "modules", "(", ")", ":", "mod_name", "=", "mod", ".", "node", ".", "name", "if", "mod_name", "==", "name", ":", "return", "mod", "# search for fullname of relative import modules", "package", "=", "node", ".", "root", "(", ")", ".", "name", "if", "mod_name", "==", "\"%s.%s\"", "%", "(", "package", ",", "name", ")", ":", "return", "mod", "if", "mod_name", "==", "\"%s.%s\"", "%", "(", "package", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", ",", "name", ")", ":", "return", "mod", "raise", "KeyError", "(", "name", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PackageDiagram.add_from_depend
add dependencies created by from-imports
pylint/pyreverse/diagrams.py
def add_from_depend(self, node, from_module): """add dependencies created by from-imports """ mod_name = node.root().name obj = self.module(mod_name) if from_module not in obj.node.depends: obj.node.depends.append(from_module)
def add_from_depend(self, node, from_module): """add dependencies created by from-imports """ mod_name = node.root().name obj = self.module(mod_name) if from_module not in obj.node.depends: obj.node.depends.append(from_module)
[ "add", "dependencies", "created", "by", "from", "-", "imports" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L241-L247
[ "def", "add_from_depend", "(", "self", ",", "node", ",", "from_module", ")", ":", "mod_name", "=", "node", ".", "root", "(", ")", ".", "name", "obj", "=", "self", ".", "module", "(", "mod_name", ")", "if", "from_module", "not", "in", "obj", ".", "node", ".", "depends", ":", "obj", ".", "node", ".", "depends", ".", "append", "(", "from_module", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
PackageDiagram.extract_relationships
extract relation ships between nodes in the diagram
pylint/pyreverse/diagrams.py
def extract_relationships(self): """extract relation ships between nodes in the diagram """ ClassDiagram.extract_relationships(self) for obj in self.classes(): # ownership try: mod = self.object_from_node(obj.node.root()) self.add_relationship(obj, mod, "ownership") except KeyError: continue for obj in self.modules(): obj.shape = "package" # dependencies for dep_name in obj.node.depends: try: dep = self.get_module(dep_name, obj.node) except KeyError: continue self.add_relationship(obj, dep, "depends")
def extract_relationships(self): """extract relation ships between nodes in the diagram """ ClassDiagram.extract_relationships(self) for obj in self.classes(): # ownership try: mod = self.object_from_node(obj.node.root()) self.add_relationship(obj, mod, "ownership") except KeyError: continue for obj in self.modules(): obj.shape = "package" # dependencies for dep_name in obj.node.depends: try: dep = self.get_module(dep_name, obj.node) except KeyError: continue self.add_relationship(obj, dep, "depends")
[ "extract", "relation", "ships", "between", "nodes", "in", "the", "diagram" ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diagrams.py#L249-L268
[ "def", "extract_relationships", "(", "self", ")", ":", "ClassDiagram", ".", "extract_relationships", "(", "self", ")", "for", "obj", "in", "self", ".", "classes", "(", ")", ":", "# ownership", "try", ":", "mod", "=", "self", ".", "object_from_node", "(", "obj", ".", "node", ".", "root", "(", ")", ")", "self", ".", "add_relationship", "(", "obj", ",", "mod", ",", "\"ownership\"", ")", "except", "KeyError", ":", "continue", "for", "obj", "in", "self", ".", "modules", "(", ")", ":", "obj", ".", "shape", "=", "\"package\"", "# dependencies", "for", "dep_name", "in", "obj", ".", "node", ".", "depends", ":", "try", ":", "dep", "=", "self", ".", "get_module", "(", "dep_name", ",", "obj", ".", "node", ")", "except", "KeyError", ":", "continue", "self", ".", "add_relationship", "(", "obj", ",", "dep", ",", "\"depends\"", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DocstringParameterChecker.visit_functiondef
Called for function and method definitions (def). :param node: Node for a function or method definition in the AST :type node: :class:`astroid.scoped_nodes.Function`
pylint/extensions/docparams.py
def visit_functiondef(self, node): """Called for function and method definitions (def). :param node: Node for a function or method definition in the AST :type node: :class:`astroid.scoped_nodes.Function` """ node_doc = utils.docstringify(node.doc, self.config.default_docstring_type) self.check_functiondef_params(node, node_doc) self.check_functiondef_returns(node, node_doc) self.check_functiondef_yields(node, node_doc)
def visit_functiondef(self, node): """Called for function and method definitions (def). :param node: Node for a function or method definition in the AST :type node: :class:`astroid.scoped_nodes.Function` """ node_doc = utils.docstringify(node.doc, self.config.default_docstring_type) self.check_functiondef_params(node, node_doc) self.check_functiondef_returns(node, node_doc) self.check_functiondef_yields(node, node_doc)
[ "Called", "for", "function", "and", "method", "definitions", "(", "def", ")", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/docparams.py#L188-L197
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "node_doc", "=", "utils", ".", "docstringify", "(", "node", ".", "doc", ",", "self", ".", "config", ".", "default_docstring_type", ")", "self", ".", "check_functiondef_params", "(", "node", ",", "node_doc", ")", "self", ".", "check_functiondef_returns", "(", "node", ",", "node_doc", ")", "self", ".", "check_functiondef_yields", "(", "node", ",", "node_doc", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DocstringParameterChecker.check_arguments_in_docstring
Check that all parameters in a function, method or class constructor on the one hand and the parameters mentioned in the parameter documentation (e.g. the Sphinx tags 'param' and 'type') on the other hand are consistent with each other. * Undocumented parameters except 'self' are noticed. * Undocumented parameter types except for 'self' and the ``*<args>`` and ``**<kwargs>`` parameters are noticed. * Parameters mentioned in the parameter documentation that don't or no longer exist in the function parameter list are noticed. * If the text "For the parameters, see" or "For the other parameters, see" (ignoring additional whitespace) is mentioned in the docstring, missing parameter documentation is tolerated. * If there's no Sphinx style, Google style or NumPy style parameter documentation at all, i.e. ``:param`` is never mentioned etc., the checker assumes that the parameters are documented in another format and the absence is tolerated. :param doc: Docstring for the function, method or class. :type doc: str :param arguments_node: Arguments node for the function, method or class constructor. :type arguments_node: :class:`astroid.scoped_nodes.Arguments` :param warning_node: The node to assign the warnings to :type warning_node: :class:`astroid.scoped_nodes.Node` :param accept_no_param_doc: Whether or not to allow no parameters to be documented. If None then this value is read from the configuration. :type accept_no_param_doc: bool or None
pylint/extensions/docparams.py
def check_arguments_in_docstring( self, doc, arguments_node, warning_node, accept_no_param_doc=None ): """Check that all parameters in a function, method or class constructor on the one hand and the parameters mentioned in the parameter documentation (e.g. the Sphinx tags 'param' and 'type') on the other hand are consistent with each other. * Undocumented parameters except 'self' are noticed. * Undocumented parameter types except for 'self' and the ``*<args>`` and ``**<kwargs>`` parameters are noticed. * Parameters mentioned in the parameter documentation that don't or no longer exist in the function parameter list are noticed. * If the text "For the parameters, see" or "For the other parameters, see" (ignoring additional whitespace) is mentioned in the docstring, missing parameter documentation is tolerated. * If there's no Sphinx style, Google style or NumPy style parameter documentation at all, i.e. ``:param`` is never mentioned etc., the checker assumes that the parameters are documented in another format and the absence is tolerated. :param doc: Docstring for the function, method or class. :type doc: str :param arguments_node: Arguments node for the function, method or class constructor. :type arguments_node: :class:`astroid.scoped_nodes.Arguments` :param warning_node: The node to assign the warnings to :type warning_node: :class:`astroid.scoped_nodes.Node` :param accept_no_param_doc: Whether or not to allow no parameters to be documented. If None then this value is read from the configuration. :type accept_no_param_doc: bool or None """ # Tolerate missing param or type declarations if there is a link to # another method carrying the same name. if not doc.doc: return if accept_no_param_doc is None: accept_no_param_doc = self.config.accept_no_param_doc tolerate_missing_params = doc.params_documented_elsewhere() # Collect the function arguments. expected_argument_names = {arg.name for arg in arguments_node.args} expected_argument_names.update(arg.name for arg in arguments_node.kwonlyargs) not_needed_type_in_docstring = self.not_needed_param_in_docstring.copy() if arguments_node.vararg is not None: expected_argument_names.add(arguments_node.vararg) not_needed_type_in_docstring.add(arguments_node.vararg) if arguments_node.kwarg is not None: expected_argument_names.add(arguments_node.kwarg) not_needed_type_in_docstring.add(arguments_node.kwarg) params_with_doc, params_with_type = doc.match_param_docs() # Tolerate no parameter documentation at all. if not params_with_doc and not params_with_type and accept_no_param_doc: tolerate_missing_params = True def _compare_missing_args(found_argument_names, message_id, not_needed_names): """Compare the found argument names with the expected ones and generate a message if there are arguments missing. :param set found_argument_names: argument names found in the docstring :param str message_id: pylint message id :param not_needed_names: names that may be omitted :type not_needed_names: set of str """ if not tolerate_missing_params: missing_argument_names = ( expected_argument_names - found_argument_names ) - not_needed_names if missing_argument_names: self.add_message( message_id, args=(", ".join(sorted(missing_argument_names)),), node=warning_node, ) def _compare_different_args(found_argument_names, message_id, not_needed_names): """Compare the found argument names with the expected ones and generate a message if there are extra arguments found. :param set found_argument_names: argument names found in the docstring :param str message_id: pylint message id :param not_needed_names: names that may be omitted :type not_needed_names: set of str """ differing_argument_names = ( (expected_argument_names ^ found_argument_names) - not_needed_names - expected_argument_names ) if differing_argument_names: self.add_message( message_id, args=(", ".join(sorted(differing_argument_names)),), node=warning_node, ) _compare_missing_args( params_with_doc, "missing-param-doc", self.not_needed_param_in_docstring ) for index, arg_name in enumerate(arguments_node.args): if arguments_node.annotations[index]: params_with_type.add(arg_name.name) _compare_missing_args( params_with_type, "missing-type-doc", not_needed_type_in_docstring ) _compare_different_args( params_with_doc, "differing-param-doc", self.not_needed_param_in_docstring ) _compare_different_args( params_with_type, "differing-type-doc", not_needed_type_in_docstring )
def check_arguments_in_docstring( self, doc, arguments_node, warning_node, accept_no_param_doc=None ): """Check that all parameters in a function, method or class constructor on the one hand and the parameters mentioned in the parameter documentation (e.g. the Sphinx tags 'param' and 'type') on the other hand are consistent with each other. * Undocumented parameters except 'self' are noticed. * Undocumented parameter types except for 'self' and the ``*<args>`` and ``**<kwargs>`` parameters are noticed. * Parameters mentioned in the parameter documentation that don't or no longer exist in the function parameter list are noticed. * If the text "For the parameters, see" or "For the other parameters, see" (ignoring additional whitespace) is mentioned in the docstring, missing parameter documentation is tolerated. * If there's no Sphinx style, Google style or NumPy style parameter documentation at all, i.e. ``:param`` is never mentioned etc., the checker assumes that the parameters are documented in another format and the absence is tolerated. :param doc: Docstring for the function, method or class. :type doc: str :param arguments_node: Arguments node for the function, method or class constructor. :type arguments_node: :class:`astroid.scoped_nodes.Arguments` :param warning_node: The node to assign the warnings to :type warning_node: :class:`astroid.scoped_nodes.Node` :param accept_no_param_doc: Whether or not to allow no parameters to be documented. If None then this value is read from the configuration. :type accept_no_param_doc: bool or None """ # Tolerate missing param or type declarations if there is a link to # another method carrying the same name. if not doc.doc: return if accept_no_param_doc is None: accept_no_param_doc = self.config.accept_no_param_doc tolerate_missing_params = doc.params_documented_elsewhere() # Collect the function arguments. expected_argument_names = {arg.name for arg in arguments_node.args} expected_argument_names.update(arg.name for arg in arguments_node.kwonlyargs) not_needed_type_in_docstring = self.not_needed_param_in_docstring.copy() if arguments_node.vararg is not None: expected_argument_names.add(arguments_node.vararg) not_needed_type_in_docstring.add(arguments_node.vararg) if arguments_node.kwarg is not None: expected_argument_names.add(arguments_node.kwarg) not_needed_type_in_docstring.add(arguments_node.kwarg) params_with_doc, params_with_type = doc.match_param_docs() # Tolerate no parameter documentation at all. if not params_with_doc and not params_with_type and accept_no_param_doc: tolerate_missing_params = True def _compare_missing_args(found_argument_names, message_id, not_needed_names): """Compare the found argument names with the expected ones and generate a message if there are arguments missing. :param set found_argument_names: argument names found in the docstring :param str message_id: pylint message id :param not_needed_names: names that may be omitted :type not_needed_names: set of str """ if not tolerate_missing_params: missing_argument_names = ( expected_argument_names - found_argument_names ) - not_needed_names if missing_argument_names: self.add_message( message_id, args=(", ".join(sorted(missing_argument_names)),), node=warning_node, ) def _compare_different_args(found_argument_names, message_id, not_needed_names): """Compare the found argument names with the expected ones and generate a message if there are extra arguments found. :param set found_argument_names: argument names found in the docstring :param str message_id: pylint message id :param not_needed_names: names that may be omitted :type not_needed_names: set of str """ differing_argument_names = ( (expected_argument_names ^ found_argument_names) - not_needed_names - expected_argument_names ) if differing_argument_names: self.add_message( message_id, args=(", ".join(sorted(differing_argument_names)),), node=warning_node, ) _compare_missing_args( params_with_doc, "missing-param-doc", self.not_needed_param_in_docstring ) for index, arg_name in enumerate(arguments_node.args): if arguments_node.annotations[index]: params_with_type.add(arg_name.name) _compare_missing_args( params_with_type, "missing-type-doc", not_needed_type_in_docstring ) _compare_different_args( params_with_doc, "differing-param-doc", self.not_needed_param_in_docstring ) _compare_different_args( params_with_type, "differing-type-doc", not_needed_type_in_docstring )
[ "Check", "that", "all", "parameters", "in", "a", "function", "method", "or", "class", "constructor", "on", "the", "one", "hand", "and", "the", "parameters", "mentioned", "in", "the", "parameter", "documentation", "(", "e", ".", "g", ".", "the", "Sphinx", "tags", "param", "and", "type", ")", "on", "the", "other", "hand", "are", "consistent", "with", "each", "other", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/docparams.py#L327-L454
[ "def", "check_arguments_in_docstring", "(", "self", ",", "doc", ",", "arguments_node", ",", "warning_node", ",", "accept_no_param_doc", "=", "None", ")", ":", "# Tolerate missing param or type declarations if there is a link to", "# another method carrying the same name.", "if", "not", "doc", ".", "doc", ":", "return", "if", "accept_no_param_doc", "is", "None", ":", "accept_no_param_doc", "=", "self", ".", "config", ".", "accept_no_param_doc", "tolerate_missing_params", "=", "doc", ".", "params_documented_elsewhere", "(", ")", "# Collect the function arguments.", "expected_argument_names", "=", "{", "arg", ".", "name", "for", "arg", "in", "arguments_node", ".", "args", "}", "expected_argument_names", ".", "update", "(", "arg", ".", "name", "for", "arg", "in", "arguments_node", ".", "kwonlyargs", ")", "not_needed_type_in_docstring", "=", "self", ".", "not_needed_param_in_docstring", ".", "copy", "(", ")", "if", "arguments_node", ".", "vararg", "is", "not", "None", ":", "expected_argument_names", ".", "add", "(", "arguments_node", ".", "vararg", ")", "not_needed_type_in_docstring", ".", "add", "(", "arguments_node", ".", "vararg", ")", "if", "arguments_node", ".", "kwarg", "is", "not", "None", ":", "expected_argument_names", ".", "add", "(", "arguments_node", ".", "kwarg", ")", "not_needed_type_in_docstring", ".", "add", "(", "arguments_node", ".", "kwarg", ")", "params_with_doc", ",", "params_with_type", "=", "doc", ".", "match_param_docs", "(", ")", "# Tolerate no parameter documentation at all.", "if", "not", "params_with_doc", "and", "not", "params_with_type", "and", "accept_no_param_doc", ":", "tolerate_missing_params", "=", "True", "def", "_compare_missing_args", "(", "found_argument_names", ",", "message_id", ",", "not_needed_names", ")", ":", "\"\"\"Compare the found argument names with the expected ones and\n generate a message if there are arguments missing.\n\n :param set found_argument_names: argument names found in the\n docstring\n\n :param str message_id: pylint message id\n\n :param not_needed_names: names that may be omitted\n :type not_needed_names: set of str\n \"\"\"", "if", "not", "tolerate_missing_params", ":", "missing_argument_names", "=", "(", "expected_argument_names", "-", "found_argument_names", ")", "-", "not_needed_names", "if", "missing_argument_names", ":", "self", ".", "add_message", "(", "message_id", ",", "args", "=", "(", "\", \"", ".", "join", "(", "sorted", "(", "missing_argument_names", ")", ")", ",", ")", ",", "node", "=", "warning_node", ",", ")", "def", "_compare_different_args", "(", "found_argument_names", ",", "message_id", ",", "not_needed_names", ")", ":", "\"\"\"Compare the found argument names with the expected ones and\n generate a message if there are extra arguments found.\n\n :param set found_argument_names: argument names found in the\n docstring\n\n :param str message_id: pylint message id\n\n :param not_needed_names: names that may be omitted\n :type not_needed_names: set of str\n \"\"\"", "differing_argument_names", "=", "(", "(", "expected_argument_names", "^", "found_argument_names", ")", "-", "not_needed_names", "-", "expected_argument_names", ")", "if", "differing_argument_names", ":", "self", ".", "add_message", "(", "message_id", ",", "args", "=", "(", "\", \"", ".", "join", "(", "sorted", "(", "differing_argument_names", ")", ")", ",", ")", ",", "node", "=", "warning_node", ",", ")", "_compare_missing_args", "(", "params_with_doc", ",", "\"missing-param-doc\"", ",", "self", ".", "not_needed_param_in_docstring", ")", "for", "index", ",", "arg_name", "in", "enumerate", "(", "arguments_node", ".", "args", ")", ":", "if", "arguments_node", ".", "annotations", "[", "index", "]", ":", "params_with_type", ".", "add", "(", "arg_name", ".", "name", ")", "_compare_missing_args", "(", "params_with_type", ",", "\"missing-type-doc\"", ",", "not_needed_type_in_docstring", ")", "_compare_different_args", "(", "params_with_doc", ",", "\"differing-param-doc\"", ",", "self", ".", "not_needed_param_in_docstring", ")", "_compare_different_args", "(", "params_with_type", ",", "\"differing-type-doc\"", ",", "not_needed_type_in_docstring", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
DocstringParameterChecker._add_raise_message
Adds a message on :param:`node` for the missing exception type. :param missing_excs: A list of missing exception types. :type missing_excs: set(str) :param node: The node show the message on. :type node: astroid.node_classes.NodeNG
pylint/extensions/docparams.py
def _add_raise_message(self, missing_excs, node): """ Adds a message on :param:`node` for the missing exception type. :param missing_excs: A list of missing exception types. :type missing_excs: set(str) :param node: The node show the message on. :type node: astroid.node_classes.NodeNG """ if node.is_abstract(): try: missing_excs.remove("NotImplementedError") except KeyError: pass if not missing_excs: return self.add_message( "missing-raises-doc", args=(", ".join(sorted(missing_excs)),), node=node )
def _add_raise_message(self, missing_excs, node): """ Adds a message on :param:`node` for the missing exception type. :param missing_excs: A list of missing exception types. :type missing_excs: set(str) :param node: The node show the message on. :type node: astroid.node_classes.NodeNG """ if node.is_abstract(): try: missing_excs.remove("NotImplementedError") except KeyError: pass if not missing_excs: return self.add_message( "missing-raises-doc", args=(", ".join(sorted(missing_excs)),), node=node )
[ "Adds", "a", "message", "on", ":", "param", ":", "node", "for", "the", "missing", "exception", "type", "." ]
PyCQA/pylint
python
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/extensions/docparams.py#L468-L489
[ "def", "_add_raise_message", "(", "self", ",", "missing_excs", ",", "node", ")", ":", "if", "node", ".", "is_abstract", "(", ")", ":", "try", ":", "missing_excs", ".", "remove", "(", "\"NotImplementedError\"", ")", "except", "KeyError", ":", "pass", "if", "not", "missing_excs", ":", "return", "self", ".", "add_message", "(", "\"missing-raises-doc\"", ",", "args", "=", "(", "\", \"", ".", "join", "(", "sorted", "(", "missing_excs", ")", ")", ",", ")", ",", "node", "=", "node", ")" ]
2bf5c61a3ff6ae90613b81679de42c0f19aea600
test
bind_cache_grant
Configures an :class:`OAuth2Provider` instance to use various caching systems to get and set the grant token. This removes the need to register :func:`grantgetter` and :func:`grantsetter` yourself. :param app: Flask application instance :param provider: :class:`OAuth2Provider` instance :param current_user: function that returns an :class:`User` object :param config_prefix: prefix for config A usage example:: oauth = OAuth2Provider(app) app.config.update({'OAUTH2_CACHE_TYPE': 'redis'}) bind_cache_grant(app, oauth, current_user) You can define which cache system you would like to use by setting the following configuration option:: OAUTH2_CACHE_TYPE = 'null' // memcache, simple, redis, filesystem For more information on the supported cache systems please visit: `Cache <http://werkzeug.pocoo.org/docs/contrib/cache/>`_
flask_oauthlib/contrib/oauth2.py
def bind_cache_grant(app, provider, current_user, config_prefix='OAUTH2'): """Configures an :class:`OAuth2Provider` instance to use various caching systems to get and set the grant token. This removes the need to register :func:`grantgetter` and :func:`grantsetter` yourself. :param app: Flask application instance :param provider: :class:`OAuth2Provider` instance :param current_user: function that returns an :class:`User` object :param config_prefix: prefix for config A usage example:: oauth = OAuth2Provider(app) app.config.update({'OAUTH2_CACHE_TYPE': 'redis'}) bind_cache_grant(app, oauth, current_user) You can define which cache system you would like to use by setting the following configuration option:: OAUTH2_CACHE_TYPE = 'null' // memcache, simple, redis, filesystem For more information on the supported cache systems please visit: `Cache <http://werkzeug.pocoo.org/docs/contrib/cache/>`_ """ cache = Cache(app, config_prefix) @provider.grantsetter def create_grant(client_id, code, request, *args, **kwargs): """Sets the grant token with the configured cache system""" grant = Grant( cache, client_id=client_id, code=code['code'], redirect_uri=request.redirect_uri, scopes=request.scopes, user=current_user(), ) log.debug("Set Grant Token with key %s" % grant.key) cache.set(grant.key, dict(grant)) @provider.grantgetter def get(client_id, code): """Gets the grant token with the configured cache system""" grant = Grant(cache, client_id=client_id, code=code) ret = cache.get(grant.key) if not ret: log.debug("Grant Token not found with key %s" % grant.key) return None log.debug("Grant Token found with key %s" % grant.key) for k, v in ret.items(): setattr(grant, k, v) return grant
def bind_cache_grant(app, provider, current_user, config_prefix='OAUTH2'): """Configures an :class:`OAuth2Provider` instance to use various caching systems to get and set the grant token. This removes the need to register :func:`grantgetter` and :func:`grantsetter` yourself. :param app: Flask application instance :param provider: :class:`OAuth2Provider` instance :param current_user: function that returns an :class:`User` object :param config_prefix: prefix for config A usage example:: oauth = OAuth2Provider(app) app.config.update({'OAUTH2_CACHE_TYPE': 'redis'}) bind_cache_grant(app, oauth, current_user) You can define which cache system you would like to use by setting the following configuration option:: OAUTH2_CACHE_TYPE = 'null' // memcache, simple, redis, filesystem For more information on the supported cache systems please visit: `Cache <http://werkzeug.pocoo.org/docs/contrib/cache/>`_ """ cache = Cache(app, config_prefix) @provider.grantsetter def create_grant(client_id, code, request, *args, **kwargs): """Sets the grant token with the configured cache system""" grant = Grant( cache, client_id=client_id, code=code['code'], redirect_uri=request.redirect_uri, scopes=request.scopes, user=current_user(), ) log.debug("Set Grant Token with key %s" % grant.key) cache.set(grant.key, dict(grant)) @provider.grantgetter def get(client_id, code): """Gets the grant token with the configured cache system""" grant = Grant(cache, client_id=client_id, code=code) ret = cache.get(grant.key) if not ret: log.debug("Grant Token not found with key %s" % grant.key) return None log.debug("Grant Token found with key %s" % grant.key) for k, v in ret.items(): setattr(grant, k, v) return grant
[ "Configures", "an", ":", "class", ":", "OAuth2Provider", "instance", "to", "use", "various", "caching", "systems", "to", "get", "and", "set", "the", "grant", "token", ".", "This", "removes", "the", "need", "to", "register", ":", "func", ":", "grantgetter", "and", ":", "func", ":", "grantsetter", "yourself", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L66-L118
[ "def", "bind_cache_grant", "(", "app", ",", "provider", ",", "current_user", ",", "config_prefix", "=", "'OAUTH2'", ")", ":", "cache", "=", "Cache", "(", "app", ",", "config_prefix", ")", "@", "provider", ".", "grantsetter", "def", "create_grant", "(", "client_id", ",", "code", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sets the grant token with the configured cache system\"\"\"", "grant", "=", "Grant", "(", "cache", ",", "client_id", "=", "client_id", ",", "code", "=", "code", "[", "'code'", "]", ",", "redirect_uri", "=", "request", ".", "redirect_uri", ",", "scopes", "=", "request", ".", "scopes", ",", "user", "=", "current_user", "(", ")", ",", ")", "log", ".", "debug", "(", "\"Set Grant Token with key %s\"", "%", "grant", ".", "key", ")", "cache", ".", "set", "(", "grant", ".", "key", ",", "dict", "(", "grant", ")", ")", "@", "provider", ".", "grantgetter", "def", "get", "(", "client_id", ",", "code", ")", ":", "\"\"\"Gets the grant token with the configured cache system\"\"\"", "grant", "=", "Grant", "(", "cache", ",", "client_id", "=", "client_id", ",", "code", "=", "code", ")", "ret", "=", "cache", ".", "get", "(", "grant", ".", "key", ")", "if", "not", "ret", ":", "log", ".", "debug", "(", "\"Grant Token not found with key %s\"", "%", "grant", ".", "key", ")", "return", "None", "log", ".", "debug", "(", "\"Grant Token found with key %s\"", "%", "grant", ".", "key", ")", "for", "k", ",", "v", "in", "ret", ".", "items", "(", ")", ":", "setattr", "(", "grant", ",", "k", ",", "v", ")", "return", "grant" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
bind_sqlalchemy
Configures the given :class:`OAuth2Provider` instance with the required getters and setters for persistence with SQLAlchemy. An example of using all models:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token, grant=Grant, current_user=current_user) You can omit any model if you wish to register the functions yourself. It is also possible to override the functions by registering them afterwards:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token) @oauth.grantgetter def get_grant(client_id, code): pass @oauth.grantsetter def set_grant(client_id, code, request, *args, **kwargs): pass # register tokensetter with oauth but keeping the tokengetter # registered by `SQLAlchemyBinding` # You would only do this for the token and grant since user and client # only have getters @oauth.tokensetter def set_token(token, request, *args, **kwargs): pass Note that current_user is only required if you're using SQLAlchemy for grant caching. If you're using another caching system with GrantCacheBinding instead, omit current_user. :param provider: :class:`OAuth2Provider` instance :param session: A :class:`Session` object :param user: :class:`User` model :param client: :class:`Client` model :param token: :class:`Token` model :param grant: :class:`Grant` model :param current_user: function that returns a :class:`User` object
flask_oauthlib/contrib/oauth2.py
def bind_sqlalchemy(provider, session, user=None, client=None, token=None, grant=None, current_user=None): """Configures the given :class:`OAuth2Provider` instance with the required getters and setters for persistence with SQLAlchemy. An example of using all models:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token, grant=Grant, current_user=current_user) You can omit any model if you wish to register the functions yourself. It is also possible to override the functions by registering them afterwards:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token) @oauth.grantgetter def get_grant(client_id, code): pass @oauth.grantsetter def set_grant(client_id, code, request, *args, **kwargs): pass # register tokensetter with oauth but keeping the tokengetter # registered by `SQLAlchemyBinding` # You would only do this for the token and grant since user and client # only have getters @oauth.tokensetter def set_token(token, request, *args, **kwargs): pass Note that current_user is only required if you're using SQLAlchemy for grant caching. If you're using another caching system with GrantCacheBinding instead, omit current_user. :param provider: :class:`OAuth2Provider` instance :param session: A :class:`Session` object :param user: :class:`User` model :param client: :class:`Client` model :param token: :class:`Token` model :param grant: :class:`Grant` model :param current_user: function that returns a :class:`User` object """ if user: user_binding = UserBinding(user, session) provider.usergetter(user_binding.get) if client: client_binding = ClientBinding(client, session) provider.clientgetter(client_binding.get) if token: token_binding = TokenBinding(token, session, current_user) provider.tokengetter(token_binding.get) provider.tokensetter(token_binding.set) if grant: if not current_user: raise ValueError(('`current_user` is required' 'for Grant Binding')) grant_binding = GrantBinding(grant, session, current_user) provider.grantgetter(grant_binding.get) provider.grantsetter(grant_binding.set)
def bind_sqlalchemy(provider, session, user=None, client=None, token=None, grant=None, current_user=None): """Configures the given :class:`OAuth2Provider` instance with the required getters and setters for persistence with SQLAlchemy. An example of using all models:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token, grant=Grant, current_user=current_user) You can omit any model if you wish to register the functions yourself. It is also possible to override the functions by registering them afterwards:: oauth = OAuth2Provider(app) bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token) @oauth.grantgetter def get_grant(client_id, code): pass @oauth.grantsetter def set_grant(client_id, code, request, *args, **kwargs): pass # register tokensetter with oauth but keeping the tokengetter # registered by `SQLAlchemyBinding` # You would only do this for the token and grant since user and client # only have getters @oauth.tokensetter def set_token(token, request, *args, **kwargs): pass Note that current_user is only required if you're using SQLAlchemy for grant caching. If you're using another caching system with GrantCacheBinding instead, omit current_user. :param provider: :class:`OAuth2Provider` instance :param session: A :class:`Session` object :param user: :class:`User` model :param client: :class:`Client` model :param token: :class:`Token` model :param grant: :class:`Grant` model :param current_user: function that returns a :class:`User` object """ if user: user_binding = UserBinding(user, session) provider.usergetter(user_binding.get) if client: client_binding = ClientBinding(client, session) provider.clientgetter(client_binding.get) if token: token_binding = TokenBinding(token, session, current_user) provider.tokengetter(token_binding.get) provider.tokensetter(token_binding.set) if grant: if not current_user: raise ValueError(('`current_user` is required' 'for Grant Binding')) grant_binding = GrantBinding(grant, session, current_user) provider.grantgetter(grant_binding.get) provider.grantsetter(grant_binding.set)
[ "Configures", "the", "given", ":", "class", ":", "OAuth2Provider", "instance", "with", "the", "required", "getters", "and", "setters", "for", "persistence", "with", "SQLAlchemy", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L121-L188
[ "def", "bind_sqlalchemy", "(", "provider", ",", "session", ",", "user", "=", "None", ",", "client", "=", "None", ",", "token", "=", "None", ",", "grant", "=", "None", ",", "current_user", "=", "None", ")", ":", "if", "user", ":", "user_binding", "=", "UserBinding", "(", "user", ",", "session", ")", "provider", ".", "usergetter", "(", "user_binding", ".", "get", ")", "if", "client", ":", "client_binding", "=", "ClientBinding", "(", "client", ",", "session", ")", "provider", ".", "clientgetter", "(", "client_binding", ".", "get", ")", "if", "token", ":", "token_binding", "=", "TokenBinding", "(", "token", ",", "session", ",", "current_user", ")", "provider", ".", "tokengetter", "(", "token_binding", ".", "get", ")", "provider", ".", "tokensetter", "(", "token_binding", ".", "set", ")", "if", "grant", ":", "if", "not", "current_user", ":", "raise", "ValueError", "(", "(", "'`current_user` is required'", "'for Grant Binding'", ")", ")", "grant_binding", "=", "GrantBinding", "(", "grant", ",", "session", ",", "current_user", ")", "provider", ".", "grantgetter", "(", "grant_binding", ".", "get", ")", "provider", ".", "grantsetter", "(", "grant_binding", ".", "set", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1