INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
check the node line number and check it if not yet done
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 for lines containing multiple statements.
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 lines have less than a maximum number of characters
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)
return the indent level of the string
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
Check if the node is being used as an iterator.
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
Checks if an import node is in the context of a conditional.
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) )
Detect when a bad built - in is referenced.
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)
Look for indexing exceptions.
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 removed attributes
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
Visit an except handler block and check for exception unpacking.
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 a raise statement and check for raising strings or old - raise - syntax.
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)
search the pylint rc file and return its path if it find it else None
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
return a validated value for an option according to its type
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)
Patch OptionParser. expand_default with custom behaviour
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))
Disable abbreviations.
def _match_long_opt(self, opt): """Disable abbreviations.""" if opt not in self._long_opt: raise optparse.BadOptionError(opt) return opt
register an options 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)
get our personal option definition and return a suitable form for use with optik/ optparse
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
optik callback for option setting
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)
set option on the correct option provider
def global_set_option(self, opt, value): """set option on the correct option provider""" self._all_options[opt].set_option(opt, value)
write a configuration file according to the current configuration into the given stream or stdout
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
read the configuration file but do not load it ( i. e. dispatching values to each options provider )
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)
dispatch values previously read from a configuration file to each options provider )
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
Override configuration according to command line parameters
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
add a dummy option section for help purpose
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)
return the usage string for available options
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()
initialize the provider using default values
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)
get the config attribute corresponding to opt
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("-", "_"))
method called to set an option ( registered in the options list )
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)
return the dictionary defining an option given its name
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 an iterator on options grouped by section
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
Determines if a BoundMethod node represents a method call.
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) )
Checks if node represents a string with complex formatting specs.
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
Clears any state left in this checker from last module checked.
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]
Checks to see if a module uses a non - Python logging module.
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 this module uses Python s built - in logging.
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 calls to logging methods.
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. log ( level format * format_args ).
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 that function call is not format_string. format ().
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 format string tokens match the supplied arguments.
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)
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.
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
return True if the node is inside a kind of for loop
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 object is an element of <nested_list > or of a nested list
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
Returns the loop node that holds the break node in arguments.
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 true if a loop may ends up in a break statement.
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 a tuple of property classes and 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
Determine the name type whose regex the a function s name should match.
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"
make a report of
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))
return True if the object is a method redefined via decorator.
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
Is this a call with exactly 1 argument where that argument is positional?
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
required method to auto register this checker
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))
Check that a Starred expression is used in an assignment target.
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 name is both nonlocal and global.
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 use of the non - existent ++ and -- operator operator
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 instantiating abstract class with abc. ABCMeta as metaclass.
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 that any loop with an else clause has a break statement.
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 a node is inside a for or while loop
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 for redefinition of a function/ method/ class name
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), )
initialize visit variables and statistics
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
check for various kind of statements without effect
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 whether or not the lambda is suspicious
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 function name docstring arguments redefinition variable names max locals
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)
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
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
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))
visit a Call node - > check if this is not a blacklisted builtin call and check for * or ** use
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)
check the use of an assert statement on a tuple.
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 duplicate key in dictionary
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 unreachable code
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 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.
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 the argument to reversed is a sequence
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 module level assigned names
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 names in a possibly recursive list <arg >
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 for a name using the type s regexp
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 the node has a non empty docstring
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 if we compare to a literal which is usually what we do not want to do.
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 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
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 for expressions like type ( x ) == Y.
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)
create the subgraphs representing any if and for statements
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)
parse the body and any else block of if and for statements
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
visit an astroid. Module node to check too complex rating and add message if is greather than max_complexity stored from options
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) )
walk to the checker s dir and collect visit and leave methods
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)
call visit events of astroid checkers for the given node recurse on its children then leave events.
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)
create a relation ship
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)
return a relation ship or None
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 visible attributes possibly with class name
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 methods
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)
create a diagram object
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)
return class names if needed in diagram
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 all class nodes in the diagram
def classes(self): """return all class nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)]
return a class by its name raise KeyError if not found
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)
extract relation ships between nodes in the diagram
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
return all module nodes in the diagram
def modules(self): """return all module nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.Module)]
return a module by its name raise KeyError if not found
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 looking also for relative imports ; raise KeyError if not found
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)
add dependencies created by from - imports
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)
extract relation ships between nodes in the diagram
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")
Called for function and method definitions ( def ).
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)
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.
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 )
Adds a message on: param: node for the missing exception type.
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 )
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.
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 the given: class: OAuth2Provider instance with the required getters and setters for persistence with SQLAlchemy.
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)