desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'get project title'
def get_title(self, obj):
return obj.title
'get label and shape for classes. The label contains all attributes and methods'
def get_values(self, obj):
label = obj.title if (obj.shape == 'interface'): label = (u'\xabinterface\xbb\\n%s' % label) if (not self.config.only_classnames): label = ('%s|%s\\l|' % (label, '\\l'.join(obj.attrs))) for func in obj.methods: label = ('%s%s()\\l' % (label, func.name)) label = ('{%s}' % label) if is_exception(obj.node): return dict(fontcolor='red', label=label, shape='record') return dict(label=label, shape='record')
'print the dot graph into <file_name>'
def close_graph(self):
self.printer.generate(self.file_name)
'initialize VCGWriter for a UML graph'
def set_printer(self, file_name, basename):
self.graph_file = open(file_name, 'w+') self.printer = VCGPrinter(self.graph_file) self.printer.open_graph(title=basename, layoutalgorithm='dfs', late_edge_labels='yes', port_sharing='no', manhattan_edges='yes') self.printer.emit_node = self.printer.node self.printer.emit_edge = self.printer.edge
'get project title in vcg format'
def get_title(self, obj):
return ('\\fb%s\\fn' % obj.title)
'get label and shape for classes. The label contains all attributes and methods'
def get_values(self, obj):
if is_exception(obj.node): label = ('\\fb\\f09%s\\fn' % obj.title) else: label = ('\\fb%s\\fn' % obj.title) if (obj.shape == 'interface'): shape = 'ellipse' else: shape = 'box' if (not self.config.only_classnames): attrs = obj.attrs methods = [func.name for func in obj.methods] maxlen = max((len(name) for name in (([obj.title] + methods) + attrs))) line = ('_' * (maxlen + 2)) label = ('%s\\n\\f%s' % (label, line)) for attr in attrs: label = ('%s\\n\\f08%s' % (label, attr)) if attrs: label = ('%s\\n\\f%s' % (label, line)) for func in methods: label = ('%s\\n\\f10%s()' % (label, func)) return dict(label=label, shape=shape)
'close graph and file'
def close_graph(self):
self.printer.close_graph() self.graph_file.close()
'create a relation ship'
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)
'return a relation ship or None'
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)
'return visible attributes, possibly with class name'
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, ass_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(ass_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):
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):
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):
names = [] for ass_node in nodes: if isinstance(ass_node, astroid.Instance): ass_node = ass_node._proxied if (isinstance(ass_node, astroid.ClassDef) and hasattr(ass_node, 'name') and (not self.has_node(ass_node))): if (ass_node.name not in names): ass_name = ass_node.name names.append(ass_name) return names
'return the list of underlying nodes'
def nodes(self):
return self._nodes.keys()
'return true if the given node is included in the diagram'
def has_node(self, node):
return (node in self._nodes)
'return the diagram object mapped to node'
def object_from_node(self, node):
return self._nodes[node]
'return all class nodes in the diagram'
def classes(self):
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):
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):
for obj in self.classes(): node = obj.node obj.attrs = self.get_attrs(node) obj.methods = self.get_methods(node) if is_interface(node): obj.shape = 'interface' else: obj.shape = 'class' 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 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 for (name, values) in (list(node.instance_attrs_type.items()) + list(node.locals_type.items())): for value in values: if (value is astroid.YES): continue if isinstance(value, astroid.Instance): value = value._proxied try: ass_obj = self.object_from_node(value) self.add_relationship(ass_obj, obj, 'association', name) except KeyError: continue
'return all module nodes in the diagram'
def modules(self):
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):
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):
for mod in self.modules(): mod_name = mod.node.name if (mod_name == name): return mod 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):
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):
ClassDiagram.extract_relationships(self) for obj in self.classes(): 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' 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')
'manage message of different type and in the context of path'
def handle_message(self, msg):
obj = msg.obj line = msg.line msg_id = msg.msg_id msg = msg.msg self.message_ids[msg_id] = 1 if obj: obj = (':%s' % obj) sigle = msg_id[0] if (PY3K and (linesep != '\n')): msg = msg.replace('\r\n', '\n') self.messages.append(('%s:%3s%s: %s' % (sigle, line, obj, msg)))
'Assert that no messages are added by the given method.'
@contextlib.contextmanager def assertNoMessages(self):
with self.assertAddsMessages(): (yield)
'Assert that exactly the given method adds the given messages. The list of messages must exactly match *all* the messages added by the method. Additionally, we check to see whether the args in each message can actually be substituted into the message string.'
@contextlib.contextmanager def assertAddsMessages(self, *messages):
(yield) got = self.linter.release_messages() msg = ('Expected messages did not match actual.\nExpected:\n%s\nGot:\n%s' % ('\n'.join((repr(m) for m in messages)), '\n'.join((repr(m) for m in got)))) assert (list(messages) == got), msg
'recursive walk on the given node'
def walk(self, node):
walker = PyLintASTWalker(linter) walker.add_checker(self.checker) walker.walk(node)
'Check that a Starred expression is used in an assignment target.'
@utils.check_messages('star-needs-assignment-target') def visit_starred(self, node):
if isinstance(node.parent, astroid.Call): return if (PY35 and isinstance(node.parent, (astroid.List, astroid.Tuple, astroid.Set, astroid.Dict))): 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):
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)))) 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'
@utils.check_messages('nonexistent-operator') 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))
'Check instantiating abstract class with abc.ABCMeta as metaclass.'
@utils.check_messages('abstract-class-instantiated') def visit_call(self, node):
try: infered = next(node.func.infer()) except astroid.InferenceError: return if (not isinstance(infered, astroid.ClassDef)): return klass = utils.node_frame_class(node) if (klass is infered): return metaclass = infered.metaclass() abstract_methods = _has_abstract_methods(infered) if (metaclass is None): for ancestor in infered.ancestors(): if ((ancestor.qname() == 'abc.ABC') and abstract_methods): self.add_message('abstract-class-instantiated', args=(infered.name,), node=node) break return if ((metaclass.qname() == 'abc.ABCMeta') and abstract_methods): self.add_message('abstract-class-instantiated', args=(infered.name,), node=node)
'Check that any loop with an else clause has a break statement.'
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, 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):
_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):
defined_self = node.parent.frame()[node.name] if ((defined_self is not node) and (not astroid.are_exclusive(node, defined_self))): self.add_message('function-redefined', node=node, args=(redeftype, defined_self.fromlineno))
'initialize visit variables and statistics'
def open(self):
self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
'check module name, docstring and required arguments'
def visit_module(self, _):
self.stats['module'] += 1
'check module name, docstring and redefinition increment branch counter'
def visit_classdef(self, node):
self.stats['class'] += 1
'check for various kind of statements without effect'
@utils.check_messages('pointless-statement', 'pointless-string-statement', 'expression-not-assigned') def visit_expr(self, node):
expr = node.value if (isinstance(expr, astroid.Const) and isinstance(expr.value, six.string_types)): 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)): return self.add_message('pointless-string-statement', node=node) return if (isinstance(expr, (astroid.Yield, astroid.Await, 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'
@utils.check_messages('unnecessary-lambda') def visit_lambda(self, node):
if node.args.defaults: return call = node.body if (not isinstance(call, astroid.Call)): return if (isinstance(node.body.func, astroid.Attribute) and isinstance(node.body.func.expr, astroid.Call)): return 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 elif (call.kwargs or call.keywords): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return 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'
@utils.check_messages('dangerous-default-value') def visit_functiondef(self, node):
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'
@utils.check_messages('unreachable', 'lost-exception') def visit_return(self, node):
self._check_unreachable(node) self._check_not_in_finally(node, 'return', (astroid.FunctionDef,))
'check is the node has a right sibling (if so, that\'s some unreachable code)'
@utils.check_messages('unreachable') def visit_continue(self, node):
self._check_unreachable(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'
@utils.check_messages('unreachable', 'lost-exception') def visit_break(self, node):
self._check_unreachable(node) self._check_not_in_finally(node, 'break', (astroid.For, astroid.While))
'check if the node has a right sibling (if so, that\'s some unreachable code)'
@utils.check_messages('unreachable') def visit_raise(self, node):
self._check_unreachable(node)
'just print a warning on exec statements'
@utils.check_messages('exec-used') def visit_exec(self, node):
self.add_message('exec-used', node=node)
'visit a CallFunc node -> check if this is not a blacklisted builtin call and check for * or ** use'
@utils.check_messages('eval-used', 'exec-used', 'bad-reversed-sequence') def visit_call(self, node):
if isinstance(node.func, astroid.Name): name = node.func.name 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.'
@utils.check_messages('assert-on-tuple') 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)
'check duplicate key in dictionary'
@utils.check_messages('duplicate-key') 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)
'update try...finally flag'
def visit_tryfinally(self, node):
self._tryfinallys.append(node)
'update try...finally flag'
def leave_tryfinally(self, node):
self._tryfinallys.pop()
'check unreachable code'
def _check_unreachable(self, node):
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=()):
if (not self._tryfinallys): return _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):
try: argument = utils.safe_infer(utils.get_argument_from_call(node, position=0)) except utils.NoSuchArgumentError: pass else: if (argument is astroid.YES): return if (argument is None): 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.Instance): if ((argument._proxied.name == 'dict') and utils.is_builtin_object(argument._proxied)): self.add_message('bad-reversed-sequence', node=node) return elif any((((ancestor.name == 'dict') and utils.is_builtin_object(ancestor)) for ancestor in argument._proxied.ancestors())): try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message('bad-reversed-sequence', node=node) return 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) elif (not isinstance(argument, (astroid.List, astroid.Tuple))): self.add_message('bad-reversed-sequence', node=node)
'check module level assigned names'
@utils.check_messages('blacklisted-name', 'invalid-name') def visit_assignname(self, node):
keyword_first_version = self._name_became_keyword_in_version(node.name, self.KEYWORD_ONSET) if (keyword_first_version is not None): self.add_message('assign-to-new-keyword', node=node, args=(node.name, keyword_first_version), confidence=interfaces.HIGH) frame = node.frame() ass_type = node.assign_type() if isinstance(ass_type, astroid.Comprehension): self._check_name('inlinevar', node.name, node) elif isinstance(frame, astroid.Module): if (isinstance(ass_type, astroid.Assign) and (not in_loop(ass_type))): if isinstance(utils.safe_infer(ass_type.value), astroid.ClassDef): self._check_name('class', node.name, node) elif (not _redefines_import(node)): self._check_name('const', node.name, node) elif isinstance(ass_type, astroid.ExceptHandler): self._check_name('variable', node.name, node) elif isinstance(frame, astroid.FunctionDef): 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):
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):
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 = getattr(self.config, (node_type + '_rgx')) 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): 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):
docstring = node.doc if (docstring is None): if (not report_missing): return if node.body: lines = ((node.body[(-1)].lineno - node.body[0].lineno) + 1) else: lines = 0 if ((node_type == 'module') and (not lines)): 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)): func = utils.safe_infer(node.body[0].value.func) if (isinstance(func, astroid.BoundMethod) and isinstance(func.bound, astroid.Instance)): if (PY3K and (func.bound.name == 'str')): return elif (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)
'visit a CallFunc node, check if map or filter are called with a lambda'
@utils.check_messages('deprecated-lambda') def visit_call(self, node):
if (not node.args): return if (not isinstance(node.args[0], astroid.Lambda)): return infered = utils.safe_infer(node.func) if (utils.is_builtin_object(infered) and (infered.name in ['map', 'filter'])): self.add_message('deprecated-lambda', node=node)
'Check if we compare to a literal, which is usually what we do not want to do.'
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 (literal.value in (True, False, None)): 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 for expressions like type(x) == Y.'
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)): right_arg = utils.safe_infer(right.args[0]) if (not isinstance(right_arg, LITERAL_NODE_TYPES)): return self.add_message('unidiomatic-typecheck', node=node)
'Clears any state left in this checker from last module checked.'
def visit_module(self, node):
self._logging_names = set() logging_mods = self.config.logging_modules 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):
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):
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.'
@check_messages(*MSGS.keys()) 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)
'Checks calls to logging.log(level, format, *format_args).'
def _check_log_method(self, node, name):
if (name == 'log'): if (node.starargs or node.kwargs or (len(node.args) < 2)): return format_pos = 1 elif (name in CHECKED_CONVENIENCE_FUNCTIONS): if (node.starargs or node.kwargs or (not node.args)): return format_pos = 0 else: return if (isinstance(node.args[format_pos], astroid.BinOp) and (node.args[format_pos].op == '%')): 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)
'Checks that function call is not format_string.format(). Args: node (astroid.node_classes.CallFunc): CallFunc AST node to be checked.'
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)
'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.'
def _check_format_string(self, node, format_arg):
num_args = _count_supplied_tokens(node.args[(format_arg + 1):]) if (not num_args): return format_string = node.args[format_arg].value if (not isinstance(format_string, six.string_types)): required_num_args = 0 else: try: (keyword_args, required_num_args) = utils.parse_format_string(format_string) if keyword_args: return 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)
'called before visiting project (i.e set of modules)'
def open(self):
self.linter.add_stats(dependencies={}) self.linter.add_stats(cycles=[]) self.stats = self.linter.stats self.import_graph = collections.defaultdict(set) self._excluded_edges = collections.defaultdict(set) self._ignored_modules = get_global_option(self, 'ignored-modules', default=[])
'called before visiting project (i.e set of modules)'
def close(self):
if self.linter.is_message_enabled('cyclic-import'): graph = self._import_graph_without_ignored_edges() vertices = list(graph) for cycle in get_cycles(graph, vertices=vertices): self.add_message('cyclic-import', args=' -> '.join(cycle))
'triggered when an import statement is seen'
@check_messages('wrong-import-position', 'multiple-imports', 'relative-import', 'reimported', 'deprecated-module') def visit_import(self, node):
self._check_reimport(node) modnode = node.root() names = [name for (name, _) in node.names] if (len(names) >= 2): self.add_message('multiple-imports', args=', '.join(names), node=node) for name in names: self._check_deprecated_module(node, name) imported_module = self._get_imported_module(node, name) if isinstance(node.parent, astroid.Module): self._check_position(node) if isinstance(node.scope(), astroid.Module): self._record_import(node, imported_module) if (imported_module is None): continue self._check_relative_import(modnode, node, imported_module, name) self._add_imported_module(node, imported_module.name)
'triggered when a from statement is seen'
@check_messages(*MSGS.keys()) def visit_importfrom(self, node):
basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_misplaced_future(node) self._check_deprecated_module(node, basename) self._check_wildcard_imports(node, imported_module) self._check_same_line_imports(node) self._check_reimport(node, basename=basename, level=node.level) if isinstance(node.parent, astroid.Module): self._check_position(node) if isinstance(node.scope(), astroid.Module): self._record_import(node, imported_module) if (imported_module is None): return modnode = node.root() self._check_relative_import(modnode, node, imported_module, basename) for (name, _) in node.names: if (name != '*'): self._add_imported_module(node, ('%s.%s' % (imported_module.name, name)))
'Check `node` import or importfrom node position is correct Send a message if `node` comes before another instruction'
def _check_position(self, node):
if self._first_non_import_node: self.add_message('wrong-import-position', node=node, args=node.as_string())
'Record the package `node` imports from'
def _record_import(self, node, importedmodnode):
importedname = (importedmodnode.name if importedmodnode else None) if (not importedname): if isinstance(node, astroid.ImportFrom): importedname = node.modname else: importedname = node.names[0][0].split('.')[0] if (isinstance(node, astroid.ImportFrom) and ((node.level or 0) >= 1)): importedname = ('.' + importedname) self._imports_stack.append((node, importedname))
'Checks imports of module `node` are grouped by category Imports must follow this order: standard, 3rd party, local'
def _check_imports_order(self, _module_node):
extern_imports = [] local_imports = [] std_imports = [] extern_not_nested = [] local_not_nested = [] isort_obj = isort.SortImports(file_contents='', known_third_party=self.config.known_third_party, known_standard_library=self.config.known_standard_library) for (node, modname) in self._imports_stack: if modname.startswith('.'): package = ('.' + modname.split('.')[1]) else: package = modname.split('.')[0] nested = (not isinstance(node.parent, astroid.Module)) import_category = isort_obj.place_module(package) if (import_category in ('FUTURE', 'STDLIB')): std_imports.append((node, package)) wrong_import = (extern_not_nested or local_not_nested) if self._is_fallback_import(node, wrong_import): continue if (wrong_import and (not nested)): self.add_message('wrong-import-order', node=node, args=(('standard import "%s"' % node.as_string()), ('"%s"' % wrong_import[0][0].as_string()))) elif (import_category in ('FIRSTPARTY', 'THIRDPARTY')): extern_imports.append((node, package)) if (not nested): extern_not_nested.append((node, package)) wrong_import = local_not_nested if (wrong_import and (not nested)): self.add_message('wrong-import-order', node=node, args=(('external import "%s"' % node.as_string()), ('"%s"' % wrong_import[0][0].as_string()))) elif (import_category == 'LOCALFOLDER'): local_imports.append((node, package)) if (not nested): local_not_nested.append((node, package)) return (std_imports, extern_imports, local_imports)
'check relative import. node is either an Import or From node, modname the imported module name.'
def _check_relative_import(self, modnode, importnode, importedmodnode, importedasname):
if (not self.linter.is_message_enabled('relative-import')): return if (importedmodnode.file is None): return False if (modnode is importedmodnode): return False if (modnode.absolute_import_activated() or getattr(importnode, 'level', None)): return False if (importedmodnode.name != importedasname): self.add_message('relative-import', args=(importedasname, importedmodnode.name), node=importnode)
'notify an imported module, used to analyze dependencies'
def _add_imported_module(self, node, importedmodname):
module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] if isinstance(node, astroid.ImportFrom): if (node.level and (node.level > 0) and (base == '__init__')): return try: importedmodname = get_module_part(importedmodname, module_file) except ImportError: pass if (context_name == importedmodname): self.add_message('import-self', node=node) elif (not is_standard_module(importedmodname)): importedmodnames = self.stats['dependencies'].setdefault(importedmodname, set()) if (context_name not in importedmodnames): importedmodnames.add(context_name) self.import_graph[context_name].add(importedmodname) if (not self.linter.is_message_enabled('cyclic-import')): self._excluded_edges[context_name].add(importedmodname)
'check if the module is deprecated'
def _check_deprecated_module(self, node, mod_path):
for mod_name in self.config.deprecated_modules: if ((mod_path == mod_name) or mod_path.startswith((mod_name + '.'))): self.add_message('deprecated-module', node=node, args=mod_path)
'check if the import is necessary (i.e. not already done)'
def _check_reimport(self, node, basename=None, level=None):
if (not self.linter.is_message_enabled('reimported')): return frame = node.frame() root = node.root() contexts = [(frame, level)] if (root is not frame): contexts.append((root, None)) for (known_context, known_level) in contexts: for (name, alias) in node.names: first = _get_first_import(node, known_context, name, basename, known_level, alias) if (first is not None): self.add_message('reimported', node=node, args=(name, first.fromlineno))
'return a verbatim layout for displaying dependencies'
def _report_external_dependencies(self, sect, _, _dummy):
dep_info = _make_tree_defs(six.iteritems(self._external_dependencies_info())) if (not dep_info): raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) sect.append(VerbatimText(tree_str))
'write dependencies as a dot (graphviz) file'
def _report_dependencies_graph(self, sect, _, _dummy):
dep_info = self.stats['dependencies'] if ((not dep_info) or (not (self.config.import_graph or self.config.ext_import_graph or self.config.int_import_graph))): raise EmptyReportError() filename = self.config.import_graph if filename: _make_graph(filename, dep_info, sect, '') filename = self.config.ext_import_graph if filename: _make_graph(filename, self._external_dependencies_info(), sect, 'external ') filename = self.config.int_import_graph if filename: _make_graph(filename, self._internal_dependencies_info(), sect, 'internal ')
'return cached external dependencies information or build and cache them'
def _external_dependencies_info(self):
if (self.__ext_dep_info is None): package = self.linter.current_name self.__ext_dep_info = result = {} for (importee, importers) in six.iteritems(self.stats['dependencies']): if (not importee.startswith(package)): result[importee] = importers return self.__ext_dep_info
'return cached internal dependencies information or build and cache them'
def _internal_dependencies_info(self):
if (self.__int_dep_info is None): package = self.linter.current_name self.__int_dep_info = result = {} for (importee, importers) in six.iteritems(self.stats['dependencies']): if importee.startswith(package): result[importee] = importers return self.__int_dep_info
'check that the accessed attribute exists to avoid too much false positives for now, we\'ll consider the code as correct if a single of the inferred nodes has the accessed attribute. function/method, super call and metaclasses are ignored'
@check_messages('no-member') def visit_attribute(self, node):
for pattern in self.config.generated_members: if re.match(pattern, node.attrname): return if re.match(pattern, node.as_string()): return try: inferred = list(node.expr.infer()) except exceptions.InferenceError: return missingattr = set() non_opaque_inference_results = [owner for owner in inferred if ((owner is not astroid.Uninferable) and (not isinstance(owner, astroid.nodes.Unknown)))] if ((len(non_opaque_inference_results) != len(inferred)) and self.config.ignore_on_opaque_inference): return for owner in non_opaque_inference_results: name = getattr(owner, 'name', None) if _is_owner_ignored(owner, name, self.config.ignored_classes, self.config.ignored_modules): continue try: if (not [n for n in owner.getattr(node.attrname) if (not isinstance(n.statement(), astroid.AugAssign))]): missingattr.add((owner, name)) continue except AttributeError: continue except exceptions.NotFoundError: if (not _emit_no_member(node, owner, name, self.config.ignore_mixin_members)): continue missingattr.add((owner, name)) continue break else: done = set() for (owner, name) in missingattr: if isinstance(owner, astroid.Instance): actual = owner._proxied else: actual = owner if (actual in done): continue done.add(actual) if self.config.missing_member_hint: hint = _missing_member_hint(owner, node.attrname, self.config.missing_member_hint_distance, self.config.missing_member_max_choices) else: hint = '' self.add_message('no-member', node=node, args=(owner.display_type(), name, node.attrname, hint), confidence=INFERENCE)
'check that if assigning to a function call, the function is possibly returning something valuable'
@check_messages('assignment-from-no-return', 'assignment-from-none') def visit_assign(self, node):
if (not isinstance(node.value, astroid.Call)): return function_node = safe_infer(node.value.func) if (not (isinstance(function_node, astroid.FunctionDef) and function_node.root().fully_defined())): return if (function_node.is_generator() or function_node.is_abstract(pass_is_abstract=False)): return returns = list(function_node.nodes_of_class(astroid.Return, skip_klass=astroid.FunctionDef)) if (not returns): self.add_message('assignment-from-no-return', node=node) else: for rnode in returns: if (not ((isinstance(rnode.value, astroid.Const) and (rnode.value.value is None)) or (rnode.value is None))): break else: self.add_message('assignment-from-none', node=node)
'Check that the given uninferable CallFunc node does not call an actual function.'
def _check_uninferable_callfunc(self, node):
if (not isinstance(node.func, astroid.Attribute)): return expr = node.func.expr klass = safe_infer(expr) if ((klass is None) or (klass is astroid.YES) or (not isinstance(klass, astroid.Instance))): return try: attrs = klass._proxied.getattr(node.func.attrname) except exceptions.NotFoundError: return for attr in attrs: if (attr is astroid.YES): continue if (not isinstance(attr, astroid.FunctionDef)): continue if decorated_with_property(attr): if all((return_node.callable() for return_node in attr.infer_call_result(node))): continue else: self.add_message('not-callable', node=node, args=node.func.as_string()) break
'check that called functions/methods are inferred to callable objects, and that the arguments passed to the function match the parameters in the inferred function\'s definition'
@check_messages(*list(MSGS.keys())) def visit_call(self, node):
call_site = astroid.arguments.CallSite.from_call(node) num_positional_args = len(call_site.positional_arguments) keyword_args = list(call_site.keyword_arguments.keys()) if isinstance(node.scope(), astroid.FunctionDef): has_no_context_positional_variadic = _no_context_variadic_positional(node) has_no_context_keywords_variadic = _no_context_variadic_keywords(node) else: has_no_context_positional_variadic = has_no_context_keywords_variadic = False called = safe_infer(node.func) if (called and (not called.callable())): if (isinstance(called, astroid.Instance) and (not has_known_bases(called))): pass else: self.add_message('not-callable', node=node, args=node.func.as_string()) self._check_uninferable_callfunc(node) try: (called, implicit_args, callable_name) = _determine_callable(called) except ValueError: return num_positional_args += implicit_args if (called.args.args is None): return if (len(called.argnames()) != len(set(called.argnames()))): return for keyword in call_site.duplicated_keywords: self.add_message('repeated-keyword', node=node, args=(keyword,)) if (call_site.has_invalid_arguments() or call_site.has_invalid_keywords()): return num_mandatory_parameters = (len(called.args.args) - len(called.args.defaults)) parameters = [] parameter_name_to_index = {} for (i, arg) in enumerate(called.args.args): if isinstance(arg, astroid.Tuple): name = None else: assert isinstance(arg, astroid.AssignName) name = arg.name parameter_name_to_index[name] = i if (i >= num_mandatory_parameters): defval = called.args.defaults[(i - num_mandatory_parameters)] else: defval = None parameters.append([(name, defval), False]) kwparams = {} for (i, arg) in enumerate(called.args.kwonlyargs): if isinstance(arg, astroid.Keyword): name = arg.arg else: assert isinstance(arg, astroid.AssignName) name = arg.name kwparams[name] = [called.args.kw_defaults[i], False] for i in range(num_positional_args): if (i < len(parameters)): parameters[i][1] = True elif (called.args.vararg is not None): break else: self.add_message('too-many-function-args', node=node, args=(callable_name,)) break for keyword in keyword_args: if (keyword in parameter_name_to_index): i = parameter_name_to_index[keyword] if parameters[i][1]: if (not ((keyword == 'self') and (called.qname() == STR_FORMAT))): self.add_message('redundant-keyword-arg', node=node, args=(keyword, callable_name)) else: parameters[i][1] = True elif (keyword in kwparams): if kwparams[keyword][1]: self.add_message('redundant-keyword-arg', node=node, args=(keyword, callable_name)) else: kwparams[keyword][1] = True elif (called.args.kwarg is not None): pass else: self.add_message('unexpected-keyword-arg', node=node, args=(keyword, callable_name)) if node.kwargs: for (i, [(name, defval), assigned]) in enumerate(parameters): if (name is not None): parameters[i][1] = True else: pass for [(name, defval), assigned] in parameters: if ((defval is None) and (not assigned)): if (name is None): display_name = '<tuple>' else: display_name = repr(name) if (not has_no_context_positional_variadic): self.add_message('no-value-for-parameter', node=node, args=(display_name, callable_name)) for name in kwparams: (defval, assigned) = kwparams[name] if ((defval is None) and (not assigned) and (not has_no_context_keywords_variadic)): self.add_message('missing-kwoa', node=node, args=(name, callable_name))
'Detect TypeErrors for unary operands.'
@check_messages('invalid-unary-operand-type') def visit_unaryop(self, node):
for error in node.type_errors(): self.add_message('invalid-unary-operand-type', args=str(error), node=node)
'Detect TypeErrors for binary arithmetic operands.'
@check_messages('unsupported-binary-operation') def _visit_binop(self, node):
self._check_binop_errors(node)
'Detect TypeErrors for augmented binary arithmetic operands.'
@check_messages('unsupported-binary-operation') def _visit_augassign(self, node):
self._check_binop_errors(node)
'checker instances should have the linter as argument linter is an object implementing ILinter'
def __init__(self, linter=None):
self.name = self.name.lower() OptionsProviderMixIn.__init__(self) self.linter = linter
'add a message of a given type'
def add_message(self, msg_id, line=None, node=None, args=None, confidence=UNDEFINED):
self.linter.add_message(msg_id, line, node, args, confidence)
'Should be overridden by subclasses.'
def process_tokens(self, tokens):
raise NotImplementedError()
'Check __slots__ in old style classes and old style class definition.'
@check_messages('slots-on-old-class', 'old-style-class') def visit_classdef(self, node):
if (('__slots__' in node) and (not node.newstyle)): confidence = (INFERENCE if has_known_bases(node) else INFERENCE_FAILURE) self.add_message('slots-on-old-class', node=node, confidence=confidence) if ((not node.bases) and (node.type == 'class') and (not node.metaclass())): self.add_message('old-style-class', node=node, confidence=HIGH)
'check property usage'
@check_messages('property-on-old-class') def visit_call(self, node):
parent = node.parent.frame() if (isinstance(parent, astroid.ClassDef) and (not parent.newstyle) and isinstance(node.func, astroid.Name)): confidence = (INFERENCE if has_known_bases(parent) else INFERENCE_FAILURE) name = node.func.name if (name == 'property'): self.add_message('property-on-old-class', node=node, confidence=confidence)
'check use of super'
@check_messages('super-on-old-class', 'bad-super-call', 'missing-super-argument') def visit_functiondef(self, node):
if (not node.is_method()): return klass = node.parent.frame() for stmt in node.nodes_of_class(astroid.Call): if (node_frame_class(stmt) != node_frame_class(node)): continue expr = stmt.func if (not isinstance(expr, astroid.Attribute)): continue call = expr.expr if (not (isinstance(call, astroid.Call) and isinstance(call.func, astroid.Name) and (call.func.name == 'super'))): continue if ((not klass.newstyle) and has_known_bases(klass)): self.add_message('super-on-old-class', node=node) else: if (not call.args): if (sys.version_info[0] == 3): continue else: self.add_message('missing-super-argument', node=call) continue arg0 = call.args[0] if (isinstance(arg0, astroid.Call) and isinstance(arg0.func, astroid.Name) and (arg0.func.name == 'type')): self.add_message('bad-super-call', node=call, args=('type',)) continue if ((len(call.args) >= 2) and isinstance(call.args[1], astroid.Name) and (call.args[1].name == 'self') and isinstance(arg0, astroid.Attribute) and (arg0.attrname == '__class__')): self.add_message('bad-super-call', node=call, args=('self.__class__',)) continue try: supcls = (call.args and next(call.args[0].infer(), None)) except astroid.InferenceError: continue if (klass is not supcls): name = None if supcls: name = supcls.name elif (call.args and hasattr(call.args[0], 'name')): name = call.args[0].name if name: self.add_message('bad-super-call', node=call, args=(name,))
'Verify that the exception context is properly set. An exception context can be only `None` or an exception.'
def _check_bad_exception_context(self, node):
cause = utils.safe_infer(node.cause) if (cause in (astroid.YES, None)): return if isinstance(cause, astroid.Const): if (cause.value is not None): self.add_message('bad-exception-context', node=node) elif ((not isinstance(cause, astroid.ClassDef)) and (not utils.inherit_from_std_ex(cause))): self.add_message('bad-exception-context', node=node)
'check for empty except'
@utils.check_messages('bare-except', 'broad-except', 'binary-op-exception', 'bad-except-order', 'catching-non-exception', 'duplicate-except') def visit_tryexcept(self, node):
exceptions_classes = [] nb_handlers = len(node.handlers) for (index, handler) in enumerate(node.handlers): if (handler.type is None): if (not utils.is_raising(handler.body)): self.add_message('bare-except', node=handler) if (index < (nb_handlers - 1)): msg = 'empty except clause should always appear last' self.add_message('bad-except-order', node=node, args=msg) elif isinstance(handler.type, astroid.BoolOp): self.add_message('binary-op-exception', node=handler, args=handler.type.op) else: try: excs = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for (part, exc) in excs: if (exc is astroid.YES): continue if (isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex(exc)): exc = exc._proxied self._check_catching_non_exception(handler, exc, part) if (not isinstance(exc, astroid.ClassDef)): continue exc_ancestors = [anc for anc in exc.ancestors() if isinstance(anc, astroid.ClassDef)] for previous_exc in exceptions_classes: if (previous_exc in exc_ancestors): msg = ('%s is an ancestor class of %s' % (previous_exc.name, exc.name)) self.add_message('bad-except-order', node=handler.type, args=msg) if ((exc.name in self.config.overgeneral_exceptions) and (exc.root().name == utils.EXCEPTIONS_MODULE) and (not utils.is_raising(handler.body))): self.add_message('broad-except', args=exc.name, node=handler.type) if (exc in exceptions_classes): self.add_message('duplicate-except', args=exc.name, node=handler.type) exceptions_classes += [exc for (_, exc) in excs]
'initialize visit variables'
def open(self):
self.stats = self.linter.add_stats() self._returns = [] self._branches = defaultdict(int)
'check size of inheritance hierarchy and number of instance attributes'
@check_messages('too-many-ancestors', 'too-many-instance-attributes', 'too-few-public-methods', 'too-many-public-methods') def visit_classdef(self, node):
nb_parents = len(list(node.ancestors())) if (nb_parents > self.config.max_parents): self.add_message('too-many-ancestors', node=node, args=(nb_parents, self.config.max_parents)) if (len(node.instance_attrs) > self.config.max_attributes): self.add_message('too-many-instance-attributes', node=node, args=(len(node.instance_attrs), self.config.max_attributes))