Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _collect_block_lines(self, msgs_store, node, msg_state):
"""Recursively walk (depth first) AST to collect block level options
line numbers.
"""
for child in node.get_children():
self._collect_block_lines(msgs_store, child, msg_state)
first = node.fromlineno
... |
def set_msg_status(self, msg, line, status):
"""Set status (enabled/disable) for a given message at a given line"""
assert line > 0
try:
self._module_msgs_state[msg.msgid][line] = status
except KeyError:
self._module_msgs_state[msg.msgid] = {line: status} |
def handle_ignored_message(
self, state_scope, msgid, line, node, args, confidence
): # pylint: disable=unused-argument
"""Report an ignored message.
state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
depending on whether the message was disabled locally in the... |
def register_report(self, reportid, r_title, r_cb, checker):
"""register a report
reportid is the unique identifier for the report
r_title the report's title
r_cb the method to call to make the report
checker is the checker defining the report
"""
reportid = repo... |
def enable_report(self, reportid):
"""disable the report of the given id"""
reportid = reportid.upper()
self._reports_state[reportid] = True |
def disable_report(self, reportid):
"""disable the report of the given id"""
reportid = reportid.upper()
self._reports_state[reportid] = False |
def make_reports(self, stats, old_stats):
"""render registered reports"""
sect = Section("Report", "%s statements analysed." % (self.stats["statement"]))
for checker in self.report_order():
for reportid, r_title, r_cb in self._reports[checker]:
if not self.report_is_e... |
def add_stats(self, **kwargs):
"""add some stats entries to the statistic dictionary
raise an AssertionError if there is a key conflict
"""
for key, value in kwargs.items():
if key[-1] == "_":
key = key[:-1]
assert key not in self.stats
... |
def get_setters_property_name(node):
"""Get the name of the property that the given node is a setter for.
:param node: The node to get the property name for.
:type node: str
:rtype: str or None
:returns: The name of the property that the node is a setter for,
or None if one could not be fo... |
def get_setters_property(node):
"""Get the property node for the given setter node.
:param node: The node to get the property for.
:type node: astroid.FunctionDef
:rtype: astroid.FunctionDef or None
:returns: The node relating to the property of the given setter node,
or None if one could ... |
def returns_something(return_node):
"""Check if a return node returns a value other than None.
:param return_node: The return node to check.
:type return_node: astroid.Return
:rtype: bool
:return: True if the return node returns a value other than None,
False otherwise.
"""
returns... |
def possible_exc_types(node):
"""
Gets all of the possible raised exception types for the given raise node.
.. note::
Caught exception types are ignored.
:param node: The raise node to find exception types for.
:type node: astroid.node_classes.NodeNG
:returns: A list of exception ty... |
def register(linter):
"""required method to auto register this checker"""
linter.register_checker(EncodingChecker(linter))
linter.register_checker(ByIdManagedMessagesChecker(linter)) |
def process_module(self, module):
"""inspect the source file to find messages activated or deactivated by id."""
managed_msgs = MessagesHandlerMixIn.get_by_id_managed_msgs()
for (mod_name, msg_id, msg_symbol, lineno, is_disabled) in managed_msgs:
if mod_name == module.name:
... |
def process_module(self, module):
"""inspect the source file to find encoding problem"""
if module.file_encoding:
encoding = module.file_encoding
else:
encoding = "ascii"
with module.stream() as stream:
for lineno, line in enumerate(stream):
... |
def process_tokens(self, tokens):
"""inspect the source to find fixme problems"""
if not self.config.notes:
return
comments = (
token_info for token_info in tokens if token_info.type == tokenize.COMMENT
)
for comment in comments:
comment_text =... |
def _is_from_future_import(stmt, name):
"""Check if the name is a future import from another module."""
try:
module = stmt.do_import_module(stmt.modname)
except astroid.AstroidBuildingException:
return None
for local_node in module.locals.get(name, []):
if isinstance(local_node,... |
def in_for_else_branch(parent, stmt):
"""Returns True if stmt in inside the else branch for a parent For stmt."""
return isinstance(parent, astroid.For) and any(
else_stmt.parent_of(stmt) or else_stmt == stmt for else_stmt in parent.orelse
) |
def overridden_method(klass, name):
"""get overridden method if any"""
try:
parent = next(klass.local_attr_ancestors(name))
except (StopIteration, KeyError):
return None
try:
meth_node = parent[name]
except KeyError:
# We have found an ancestor defining <name> but it'... |
def _get_unpacking_extra_info(node, infered):
"""return extra information to add to the message for unpacking-non-sequence
and unbalanced-tuple-unpacking errors
"""
more = ""
infered_module = infered.root().name
if node.root().name == infered_module:
if node.lineno == infered.lineno:
... |
def _detect_global_scope(node, frame, defframe):
""" Detect that the given frames shares a global
scope.
Two frames shares a global scope when neither
of them are hidden under a function scope, as well
as any of parent scope of them, until the root scope.
In this case, depending from something ... |
def _fix_dot_imports(not_consumed):
""" Try to fix imports with multiple dots, by returning a dictionary
with the import names expanded. The function unflattens root imports,
like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
and 'xml.sax' respectively.
"""
# TODO: this sho... |
def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imp... |
def _assigned_locally(name_node):
"""
Checks if name_node has corresponding assign statement in same scope
"""
assign_stmts = name_node.scope().nodes_of_class(astroid.AssignName)
return any(a.name == name_node.name for a in assign_stmts) |
def mark_as_consumed(self, name, new_node):
"""
Mark the name as consumed and delete it from
the to_consume dictionary
"""
self.consumed[name] = new_node
del self.to_consume[name] |
def visit_module(self, node):
"""visit module : update consumption analysis variable
checks globals doesn't overrides builtins
"""
self._to_consume = [NamesConsumer(node, "module")]
self._postponed_evaluation_enabled = is_postponed_evaluation_enabled(node)
for name, stmt... |
def leave_module(self, node):
"""leave module: check globals
"""
assert len(self._to_consume) == 1
not_consumed = self._to_consume.pop().to_consume
# attempt to check for __all__ if defined
if "__all__" in node.locals:
self._check_all(node, not_consumed)
... |
def visit_functiondef(self, node):
"""visit function: update consumption analysis variable and check locals
"""
self._to_consume.append(NamesConsumer(node, "function"))
if not (
self.linter.is_message_enabled("redefined-outer-name")
or self.linter.is_message_enabl... |
def leave_functiondef(self, node):
"""leave function: check function's locals are consumed"""
if node.type_comment_returns:
self._store_type_annotation_node(node.type_comment_returns)
if node.type_comment_args:
for argument_annotation in node.type_comment_args:
... |
def visit_global(self, node):
"""check names imported exists in the global scope"""
frame = node.frame()
if isinstance(frame, astroid.Module):
self.add_message("global-at-module-level", node=node)
return
module = frame.root()
default_message = True
... |
def _ignore_class_scope(self, node):
"""
Return True if the node is in a local class scope, as an assignment.
:param node: Node considered
:type node: astroid.Node
:return: True if the node is in a local class scope, as an assignment. False otherwise.
:rtype: bool
... |
def visit_name(self, node):
"""check that a name is defined if the current scope and doesn't
redefine a built-in
"""
stmt = node.statement()
if stmt.fromlineno is None:
# name node from an astroid built from live code, skip
assert not stmt.root().file.ends... |
def _has_homonym_in_upper_function_scope(self, node, index):
"""
Return True if there is a node with the same name in the to_consume dict of an upper scope
and if that scope is a function
:param node: node to check for
:type node: astroid.Node
:param index: index of the ... |
def visit_import(self, node):
"""check modules attribute accesses"""
if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
# No need to verify this, since ImportError is already
# handled by the client code.
return
for name, _ in node.n... |
def visit_importfrom(self, node):
"""check modules attribute accesses"""
if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
# No need to verify this, since ImportError is already
# handled by the client code.
return
name_parts = node... |
def visit_assign(self, node):
"""Check unbalanced tuple unpacking for assignments
and unpacking non-sequences as well as in case self/cls
get assigned.
"""
self._check_self_cls_assign(node)
if not isinstance(node.targets[0], (astroid.Tuple, astroid.List)):
ret... |
def _check_self_cls_assign(self, node):
"""Check that self/cls don't get assigned"""
assign_names = {
target.name
for target in node.targets
if isinstance(target, astroid.AssignName)
}
scope = node.scope()
nonlocals_with_same_name = any(
... |
def _check_unpacking(self, infered, node, targets):
""" Check for unbalanced tuple unpacking
and unpacking non sequences.
"""
if utils.is_inside_abstract_class(node):
return
if utils.is_comprehension(node):
return
if infered is astroid.Uninferable:... |
def _check_module_attrs(self, node, module, module_names):
"""check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
assert isinstance(module, astroid.Module), module
while module_n... |
def _check_metaclasses(self, node):
""" Update consumption analysis for metaclasses. """
consumed = [] # [(scope_locals, consumed_key)]
for child_node in node.get_children():
if isinstance(child_node, astroid.ClassDef):
consumed.extend(self._check_classdef_metaclass... |
def table_lines_from_stats(stats, _, columns):
"""get values listed in <columns> from <stats> and <old_stats>,
and return a formated list of values, designed to be given to a
ureport.Table object
"""
lines = []
for m_type in columns:
new = stats[m_type]
new = "%.3f" % new if isin... |
def ensure_scripts(linux_scripts):
"""Creates the proper script names required for each platform
(taken from 4Suite)
"""
from distutils import util
if util.get_platform()[:3] == "win":
return linux_scripts + [script + ".bat" for script in linux_scripts]
return linux_scripts |
def get_packages(directory, prefix):
"""return a list of subpackages for the given directory"""
result = []
for package in os.listdir(directory):
absfile = join(directory, package)
if isdir(absfile):
if exists(join(absfile, "__init__.py")):
if prefix:
... |
def install(**kwargs):
"""setup entry point"""
if USE_SETUPTOOLS:
if "--force-manifest" in sys.argv:
sys.argv.remove("--force-manifest")
packages = [modname] + get_packages(join(base_dir, "pylint"), modname)
if USE_SETUPTOOLS:
if install_requires:
kwargs["install_... |
def run(self):
"""overridden from install_lib class"""
install_lib.install_lib.run(self)
# manually install included directories if any
if include_dirs:
for directory in include_dirs:
dest = join(self.install_dir, directory)
if sys.version_info... |
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports):
"""return lines with leading/trailing whitespace and any ignored code
features removed
"""
if ignore_imports:
tree = astroid.parse("".join(lines))
node_is_import_by_lineno = (
(node.lineno, isinsta... |
def report_similarities(sect, stats, old_stats):
"""make a layout with some stats about duplication"""
lines = ["", "now", "previous", "difference"]
lines += table_lines_from_stats(
stats, old_stats, ("nb_duplicated_lines", "percent_duplicated_lines")
)
sect.append(Table(children=lines, cols... |
def Run(argv=None):
"""standalone command line access point"""
if argv is None:
argv = sys.argv[1:]
from getopt import getopt
s_opts = "hdi"
l_opts = (
"help",
"duplicates=",
"ignore-comments",
"ignore-imports",
"ignore-docstrings",
)
min_line... |
def append_stream(self, streamid, stream, encoding=None):
"""append a file to search for similarities"""
if encoding is None:
readlines = stream.readlines
else:
readlines = decoding_stream(stream, encoding).readlines
try:
self.linesets.append(
... |
def _compute_sims(self):
"""compute similarities in appended files"""
no_duplicates = defaultdict(list)
for num, lineset1, idx1, lineset2, idx2 in self._iter_sims():
duplicate = no_duplicates[num]
for couples in duplicate:
if (lineset1, idx1) in couples or... |
def _display_sims(self, sims):
"""display computed similarities on stdout"""
nb_lignes_dupliquees = 0
for num, couples in sims:
print()
print(num, "similar lines in", len(couples), "files")
couples = sorted(couples)
for lineset, idx in couples:
... |
def _find_common(self, lineset1, lineset2):
"""find similarities in the two given linesets"""
lines1 = lineset1.enumerate_stripped
lines2 = lineset2.enumerate_stripped
find = lineset2.find
index1 = 0
min_lines = self.min_lines
while index1 < len(lineset1):
... |
def _iter_sims(self):
"""iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
for sim in self._find_common(lineset, lineset2):
... |
def enumerate_stripped(self, start_at=0):
"""return an iterator on stripped lines, starting from a given index
if specified, else 0
"""
idx = start_at
if start_at:
lines = self._stripped_lines[start_at:]
else:
lines = self._stripped_lines
f... |
def _mk_index(self):
"""create the index for this set"""
index = defaultdict(list)
for line_no, line in enumerate(self._stripped_lines):
if line:
index[line].append(line_no)
return index |
def set_option(self, optname, value, action=None, optdict=None):
"""method called to set an option (registered in the options list)
overridden to report options setting to Similar
"""
BaseChecker.set_option(self, optname, value, action, optdict)
if optname == "min-similarity-lin... |
def open(self):
"""init the checkers: reset linesets and statistics information"""
self.linesets = []
self.stats = self.linter.add_stats(
nb_duplicated_lines=0, percent_duplicated_lines=0
) |
def process_module(self, node):
"""process a module
the module's content is accessible via the stream object
stream must implement the readlines method
"""
with node.stream() as stream:
self.append_stream(self.linter.current_name, stream, node.file_encoding) |
def close(self):
"""compute and display similarities on closing (i.e. end of parsing)"""
total = sum(len(lineset) for lineset in self.linesets)
duplicated = 0
stats = self.stats
for num, couples in self._compute_sims():
msg = []
for lineset, idx in couples... |
def _definition_equivalent_to_call(definition, call):
"""Check if a definition signature is equivalent to a call."""
if definition.kwargs:
same_kw_variadics = definition.kwargs in call.starred_kws
else:
same_kw_variadics = not call.starred_kws
if definition.varargs:
same_args_var... |
def _check_arg_equality(node_a, node_b, attr_name):
"""
Check equality of nodes based on the comparison of their attributes named attr_name.
Args:
node_a (astroid.node): first node to compare.
node_b (astroid.node): second node to compare.
attr_name (str): name of the nodes attribut... |
def _has_different_parameters_default_value(original, overridden):
"""
Check if original and overridden methods arguments have different default values
Return True if one of the overridden arguments has a default
value different from the default value of the original argument
If one of the method d... |
def _different_parameters(original, overridden, dummy_parameter_regex):
"""Determine if the two methods have different parameters
They are considered to have different parameters if:
* they have different positional parameters, including different names
* one of the methods is having variadics,... |
def _called_in_methods(func, klass, methods):
""" Check if the func was called in any of the given methods,
belonging to the *klass*. Returns True if so, False otherwise.
"""
if not isinstance(func, astroid.FunctionDef):
return False
for method in methods:
try:
infered = ... |
def _is_attribute_property(name, klass):
""" Check if the given attribute *name* is a property
in the given *klass*.
It will look for `property` calls or for functions
with the given name, decorated by `property` or `property`
subclasses.
Returns ``True`` if the name is a property in the given ... |
def _safe_infer_call_result(node, caller, context=None):
"""
Safely infer the return value of a function.
Returns None if inference failed or if there is some ambiguity (more than
one node has been inferred). Otherwise returns infered value.
"""
try:
inferit = node.infer_call_result(cal... |
def _ancestors_to_call(klass_node, method="__init__"):
"""return a dictionary where keys are the list of base classes providing
the queried method, and so that should/may be called from the method node
"""
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_... |
def register(linter):
"""required method to auto register this checker """
linter.register_checker(ClassChecker(linter))
linter.register_checker(SpecialMethodsChecker(linter)) |
def set_accessed(self, node):
"""Set the given node as accessed."""
frame = node_frame_class(node)
if frame is None:
# The node does not live in a class.
return
self._scopes[frame][node.attrname].append(node) |
def visit_classdef(self, node):
"""init visit variable _accessed
"""
self._check_bases_classes(node)
# if not an exception or a metaclass
if node.type == "class" and has_known_bases(node):
try:
node.local_attr("__init__")
except astroid.Not... |
def _check_consistent_mro(self, node):
"""Detect that a class has a consistent mro or duplicate bases."""
try:
node.mro()
except InconsistentMroError:
self.add_message("inconsistent-mro", args=node.name, node=node)
except DuplicateBasesError:
self.add_... |
def _check_proper_bases(self, node):
"""
Detect that a class inherits something which is not
a class or a type.
"""
for base in node.bases:
ancestor = safe_infer(base)
if ancestor in (astroid.Uninferable, None):
continue
if isin... |
def leave_classdef(self, cnode):
"""close a class node:
check that instance attributes are defined in __init__ and check
access to existent members
"""
# check access to existent members on non metaclass classes
if self._ignore_mixin and cnode.name[-5:].lower() == "mixin"... |
def visit_functiondef(self, node):
"""check method arguments, overriding"""
# ignore actual functions
if not node.is_method():
return
self._check_useless_super_delegation(node)
klass = node.parent.frame()
self._meth_could_be_func = True
# check first... |
def _check_useless_super_delegation(self, function):
"""Check if the given function node is an useless method override
We consider it *useless* if it uses the super() builtin, but having
nothing additional whatsoever than not implementing the method at all.
If the method uses super() to... |
def leave_functiondef(self, node):
"""on method node, check if this method couldn't be a function
ignore class, static and abstract methods, initializer,
methods overridden from a parent class.
"""
if node.is_method():
if node.args.args is not None:
s... |
def visit_attribute(self, node):
"""check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods)
"""
# Check self
if self._uses_mandatory_method_para... |
def _check_in_slots(self, node):
""" Check that the given AssignAttr node
is defined in the class slots.
"""
inferred = safe_infer(node.expr)
if not isinstance(inferred, astroid.Instance):
return
klass = inferred._proxied
if not has_known_bases(klass)... |
def _check_classmethod_declaration(self, node):
"""Checks for uses of classmethod() or staticmethod()
When a @classmethod or @staticmethod decorator should be used instead.
A message will be emitted only if the assignment is at a class scope
and only if the classmethod's argument belong... |
def _check_protected_attribute_access(self, node):
"""Given an attribute access node (set or get), check if attribute
access is legitimate. Call _check_first_attr with node before calling
this method. Valid cases are:
* self._attr in a method or cls._attr in a classmethod. Checked by
... |
def visit_name(self, node):
"""check if the name handle an access to a class member
if so, register it
"""
if self._first_attrs and (
node.name == self._first_attrs[-1] or not self._first_attrs[-1]
):
self._meth_could_be_func = False |
def _check_accessed_members(self, node, accessed):
"""check that accessed members are defined"""
# XXX refactor, probably much simpler now that E0201 is in type checker
excs = ("AttributeError", "Exception", "BaseException")
for attr, nodes in accessed.items():
try:
... |
def _check_first_arg_for_type(self, node, metaclass=0):
"""check the name of first argument, expect:
* 'self' for a regular method
* 'cls' for a class method or a metaclass regular method (actually
valid-classmethod-first-arg value)
* 'mcs' for a metaclass class method (actual... |
def _check_bases_classes(self, node):
"""check that the given class node implements abstract methods from
base classes
"""
def is_abstract(method):
return method.is_abstract(pass_is_abstract=False)
# check if this class abstract
if class_is_abstract(node):
... |
def _check_init(self, node):
"""check that the __init__ method call super or ancestors'__init__
method
"""
if not self.linter.is_message_enabled(
"super-init-not-called"
) and not self.linter.is_message_enabled("non-parent-init-called"):
return
kla... |
def _check_signature(self, method1, refmethod, class_type, cls):
"""check that the signature of the two given methods match
"""
if not (
isinstance(method1, astroid.FunctionDef)
and isinstance(refmethod, astroid.FunctionDef)
):
self.add_message(
... |
def _is_mandatory_method_param(self, node):
"""Check if astroid.Name corresponds to first attribute variable name
Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
"""
return (
self._first_attrs
and isinstance(node, astroid.Name)
... |
def _annotated_unpack_infer(stmt, context=None):
"""
Recursively generate nodes inferred by the given statement.
If the inferred value is a list or a tuple, recurse on the elements.
Returns an iterator which yields tuples in the format
('original node', 'infered node').
"""
if isinstance(stm... |
def _is_raising(body: typing.List) -> bool:
"""Return true if the given statement node raise an exception"""
for node in body:
if isinstance(node, astroid.Raise):
return True
return False |
def _check_bad_exception_context(self, node):
"""Verify that the exception context is properly set.
An exception context can be only `None` or an exception.
"""
cause = utils.safe_infer(node.cause)
if cause in (astroid.Uninferable, None):
return
if isinstanc... |
def visit_tryexcept(self, node):
"""check for empty except"""
self._check_try_except_raise(node)
exceptions_classes = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handle... |
def visit_functiondef(self, node):
"""check use of super"""
# ignore actual functions or method within a new style class
if not node.is_method():
return
klass = node.parent.frame()
for stmt in node.nodes_of_class(astroid.Call):
if node_frame_class(stmt) !=... |
def display_reports(self, layout):
"""display results encapsulated in the layout tree"""
self.section = 0
if hasattr(layout, "report_id"):
layout.children[0].children[0].data += " (%s)" % layout.report_id
self._display(layout) |
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool:
"""Check if a class node is a typing.NamedTuple class"""
for base in node.ancestors():
if base.qname() == TYPING_NAMEDTUPLE:
return True
return False |
def _is_enum_class(node: astroid.ClassDef) -> bool:
"""Check if a class definition defines an Enum class.
:param node: The class node to check.
:type node: astroid.ClassDef
:returns: True if the given node represents an Enum class. False otherwise.
:rtype: bool
"""
for base in node.bases:
... |
def _is_dataclass(node: astroid.ClassDef) -> bool:
"""Check if a class definition defines a Python 3.7+ dataclass
:param node: The class node to check.
:type node: astroid.ClassDef
:returns: True if the given node represents a dataclass class. False otherwise.
:rtype: bool
"""
if not node.... |
def _count_boolean_expressions(bool_op):
"""Counts the number of boolean expressions in BoolOp `bool_op` (recursive)
example: a and (b or c or (d and e)) ==> 5 boolean expressions
"""
nb_bool_expr = 0
for bool_expr in bool_op.get_children():
if isinstance(bool_expr, BoolOp):
nb_... |
def open(self):
"""initialize visit variables"""
self.stats = self.linter.add_stats()
self._returns = []
self._branches = defaultdict(int)
self._stmts = [] |
def visit_classdef(self, node):
"""check size of inheritance hierarchy and number of instance attributes
"""
nb_parents = len(list(node.ancestors()))
if nb_parents > self.config.max_parents:
self.add_message(
"too-many-ancestors",
node=node,
... |
def leave_classdef(self, node):
"""check number of public methods"""
my_methods = sum(
1 for method in node.mymethods() if not method.name.startswith("_")
)
# Does the class contain less than n public methods ?
# This checks only the methods defined in the current cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.