INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Checks for uses of classmethod () or staticmethod () | 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... |
Given an attribute access node ( set or get ) check if attribute access is legitimate. Call _check_first_attr with node before calling this method. Valid cases are: * self. _attr in a method or cls. _attr in a classmethod. Checked by _check_first_attr. * Klass. _attr inside Klass class. * Klass2. _attr inside Klass cla... | def _check_protected_attribute_access(self, node):
"""Given an attribute access node (set or get), check if attribute
access is legitimate. Call _check_first_attr with node before calling
this method. Valid cases are:
* self._attr in a method or cls._attr in a classmethod. Checked by
... |
check if the name handle an access to a class member if so register it | def visit_name(self, node):
"""check if the name handle an access to a class member
if so, register it
"""
if self._first_attrs and (
node.name == self._first_attrs[-1] or not self._first_attrs[-1]
):
self._meth_could_be_func = False |
check that accessed members are defined | 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:
... |
check the name of first argument expect: | 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... |
check that the given class node implements abstract methods from base classes | 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):
... |
check that the __init__ method call super or ancestors __init__ method | 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... |
check that the signature of the two given methods match | 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(
... |
Check if astroid. Name corresponds to first attribute variable name | 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)
... |
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 ). | 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... |
Return true if the given statement node raise an exception | 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 |
Verify that the exception context is properly set. | 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... |
check for empty except | 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... |
check use of super | 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) !=... |
display results encapsulated in the layout tree | 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) |
Check if a class node is a typing. NamedTuple class | def _is_typing_namedtuple(node: astroid.ClassDef) -> bool:
"""Check if a class node is a typing.NamedTuple class"""
for base in node.ancestors():
if base.qname() == TYPING_NAMEDTUPLE:
return True
return False |
Check if a class definition defines an Enum class. | 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:
... |
Check if a class definition defines a Python 3. 7 + dataclass | 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.... |
Counts the number of boolean expressions in BoolOp bool_op ( recursive ) | 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_... |
initialize visit variables | def open(self):
"""initialize visit variables"""
self.stats = self.linter.add_stats()
self._returns = []
self._branches = defaultdict(int)
self._stmts = [] |
check size of inheritance hierarchy and number of instance attributes | def visit_classdef(self, node):
"""check size of inheritance hierarchy and number of instance attributes
"""
nb_parents = len(list(node.ancestors()))
if nb_parents > self.config.max_parents:
self.add_message(
"too-many-ancestors",
node=node,
... |
check number of public methods | def leave_classdef(self, node):
"""check number of public methods"""
my_methods = sum(
1 for method in node.mymethods() if not method.name.startswith("_")
)
# Does the class contain less than n public methods ?
# This checks only the methods defined in the current cl... |
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
"""
# init branch and returns counters
self._returns.append(0)
# check number of arguments
args = node.args.args
ignored_argument_name... |
most of the work is done here on close: checks for max returns branch return in __init__ | def leave_functiondef(self, node):
"""most of the work is done here on close:
checks for max returns, branch, return in __init__
"""
returns = self._returns.pop()
if returns > self.config.max_returns:
self.add_message(
"too-many-return-statements",
... |
increments the branches counter | def visit_tryexcept(self, node):
"""increments the branches counter"""
branches = len(node.handlers)
if node.orelse:
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches) |
increments the branches counter and checks boolean expressions | def visit_if(self, node):
"""increments the branches counter and checks boolean expressions"""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (len(node.orelse) > 1 or not isinstance(node.orelse[0], If)):... |
Go through if node node and counts its boolean expressions | def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and counts its boolean expressions
if the "if" node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, BoolOp):
return
nb_bool_expr = _count_boolean_expressio... |
increments the branches counter | def visit_while(self, node):
"""increments the branches counter"""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches) |
check the node has any spelling errors | def _check_docstring(self, node):
"""check the node has any spelling errors"""
docstring = node.doc
if not docstring:
return
start_line = node.lineno + 1
# Go through lines of docstring
for idx, line in enumerate(docstring.splitlines()):
self._ch... |
Format the message according to the given template. | def format(self, template):
"""Format the message according to the given template.
The template format is the one of the format method :
cf. http://docs.python.org/2/library/string.html#formatstrings
"""
# For some reason, _asdict on derived namedtuples does not work with
... |
Checks if node is len ( SOMETHING ). | def _is_len_call(node):
"""Checks if node is len(SOMETHING)."""
return (
isinstance(node, astroid.Call)
and isinstance(node.func, astroid.Name)
and node.func.name == "len"
) |
Check if the given token is a trailing comma | def _is_trailing_comma(tokens, index):
"""Check if the given token is a trailing comma
:param tokens: Sequence of modules tokens
:type tokens: list[tokenize.TokenInfo]
:param int index: Index of token under check in tokens
:returns: True if the token is a comma which trails an expression
:rtype... |
Required method to auto register this checker. | def register(linter):
"""Required method to auto register this checker."""
linter.register_checker(RefactoringChecker(linter))
linter.register_checker(NotChecker(linter))
linter.register_checker(RecommandationChecker(linter))
linter.register_checker(LenChecker(linter)) |
Check if the given node is an actual elif | def _is_actual_elif(self, node):
"""Check if the given node is an actual elif
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
Unfortunately we need to know the exact type in certain
cases.
"""
... |
Check if the given if node can be simplified. | def _check_simplifiable_if(self, node):
"""Check if the given if node can be simplified.
The if statement can be reduced to a boolean expression
in some cases. For instance, if there are two branches
and both of them return a boolean value that depends on
the result of the state... |
Check if an exception of type StopIteration is raised inside a generator | def _check_stop_iteration_inside_generator(self, node):
"""Check if an exception of type StopIteration is raised inside a generator"""
frame = node.frame()
if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator():
return
if utils.node_ignores_exception(node, ... |
Return True if the exception node in argument inherit from StopIteration | def _check_exception_inherit_from_stopiteration(exc):
"""Return True if the exception node in argument inherit from StopIteration"""
stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE)
return any(_class.qname() == stopiteration_qname for _class in exc.mro()) |
Check if a StopIteration exception is raised by the call to next function | def _check_raising_stopiteration_in_generator_next_call(self, node):
"""Check if a StopIteration exception is raised by the call to next function
If the next value has a default value, then do not add message.
:param node: Check to see if this Call node is a next function
:type node: :... |
Update and check the number of nested blocks | def _check_nested_blocks(self, node):
"""Update and check the number of nested blocks
"""
# only check block levels inside functions or methods
if not isinstance(node.scope(), astroid.FunctionDef):
return
# messages are triggered on leaving the nested block. Here we s... |
Get the duplicated types from the underlying isinstance calls. | def _duplicated_isinstance_types(node):
"""Get the duplicated types from the underlying isinstance calls.
:param astroid.BoolOp node: Node which should contain a bunch of isinstance calls.
:returns: Dictionary of the comparison objects from the isinstance calls,
to duplicate v... |
Check isinstance calls which can be merged together. | def _check_consider_merging_isinstance(self, node):
"""Check isinstance calls which can be merged together."""
if node.op != "or":
return
first_args = self._duplicated_isinstance_types(node)
for duplicated_name, class_names in first_args.items():
names = sorted(n... |
Check if there is any chained comparison in the expression. | def _check_chained_comparison(self, node):
"""Check if there is any chained comparison in the expression.
Add a refactoring message if a boolOp contains comparison like a < b and b < c,
which can be chained as a < b < c.
Care is taken to avoid simplifying a < b < c and b < d.
"... |
We start with the augmented assignment and work our way upwards. Names of variables for nodes if match successful: result = # assign for number in [ 1 2 3 ] # for_loop result + = number # aug_assign | def _check_consider_using_join(self, aug_assign):
"""
We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
result += number # aug_assign
... |
Returns true if node is condition and true_value or false_value form. | def _is_and_or_ternary(node):
"""
Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, astroid.BoolOp)
and node.op ==... |
Check that all return statements inside a function are consistent. | def _check_consistent_returns(self, node):
"""Check that all return statements inside a function are consistent.
Return statements are consistent if:
- all returns are explicit and if there is no implicit return;
- all returns are empty and if there is, possibly, an implicit ret... |
Check if the node ends with an explicit return statement. | def _is_node_return_ended(self, node):
"""Check if the node ends with an explicit return statement.
Args:
node (astroid.NodeNG): node to be checked.
Returns:
bool: True if the node ends with an explicit statement, False otherwise.
"""
# Recursion base ... |
Check for presence of a * single * return statement at the end of a function. return or return None are useless because None is the default return type if they are missing. | def _check_return_at_the_end(self, node):
"""Check for presence of a *single* return statement at the end of a
function. "return" or "return None" are useless because None is the
default return type if they are missing.
NOTE: produces a message only if there is a single return statement... |
Emit a convention whenever range and len are used for indexing. | def visit_for(self, node):
"""Emit a convention whenever range and len are used for indexing."""
# Verify that we have a `range([start], len(...), [stop])` call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper range call?
... |
not len ( S ) must become not S regardless if the parent block is a test condition or something else ( boolean expression ) e. g. if not len ( S ): | def visit_unaryop(self, node):
"""`not len(S)` must become `not S` regardless if the parent block
is a test condition or something else (boolean expression)
e.g. `if not len(S):`"""
if (
isinstance(node, astroid.UnaryOp)
and node.op == "not"
and _is_le... |
check if we need graphviz for different output format | def _check_graphviz_available(output_format):
"""check if we need graphviz for different output format"""
try:
subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
print(
"The output format '%s' is currently not available.\n"
... |
checking arguments and run project | def run(self, args):
"""checking arguments and run project"""
if not args:
print(self.help())
return 1
# insert current working directory to the python path to recognize
# dependencies to local modules even if cwd is not in the PYTHONPATH
sys.path.insert(0... |
check for empty except | def visit_tryexcept(self, node):
"""check for empty except"""
for handler in node.handlers:
if handler.type is None:
continue
if isinstance(handler.type, astroid.BoolOp):
continue
try:
excs = list(_annotated_unpack_infer... |
write files for <project > according to <diadefs > | def write(self, diadefs):
"""write files for <project> according to <diadefs>
"""
for diagram in diadefs:
basename = diagram.title.strip().replace(" ", "_")
file_name = "%s.%s" % (basename, self.config.output_format)
self.set_printer(file_name, basename)
... |
write a package diagram | def write_packages(self, diagram):
"""write a package diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.modules(), key=lambda x: x.title)):
self.printer.emit_node(i, label=self.get_title(obj), shape="box")
obj.fig_id = ... |
write a class diagram | def write_classes(self, diagram):
"""write a class diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)):
self.printer.emit_node(i, **self.get_values(obj))
obj.fig_id = i
# inheritan... |
initialize DotWriter and add options for layout. | def set_printer(self, file_name, basename):
"""initialize DotWriter and add options for layout.
"""
layout = dict(rankdir="BT")
self.printer = DotBackend(basename, additional_param=layout)
self.file_name = file_name |
get label and shape for classes. | def get_values(self, obj):
"""get label and shape for classes.
The label contains all attributes and methods
"""
label = obj.title
if obj.shape == "interface":
label = "«interface»\\n%s" % label
if not self.config.only_classnames:
label = r"%s|%s\... |
initialize VCGWriter for a UML graph | def set_printer(self, file_name, basename):
"""initialize VCGWriter for a UML graph"""
self.graph_file = open(file_name, "w+")
self.printer = VCGPrinter(self.graph_file)
self.printer.open_graph(
title=basename,
layoutalgorithm="dfs",
late_edge_labels="... |
get label and shape for classes. | def get_values(self, obj):
"""get label and shape for classes.
The label contains all attributes and methods
"""
if is_exception(obj.node):
label = r"\fb\f09%s\fn" % obj.title
else:
label = r"\fb%s\fn" % obj.title
if obj.shape == "interface":
... |
return True if message may be emitted using the current interpreter | def may_be_emitted(self):
"""return True if message may be emitted using the current interpreter"""
if self.minversion is not None and self.minversion > sys.version_info:
return False
if self.maxversion is not None and self.maxversion <= sys.version_info:
return False
... |
return the help string for the given message id | def format_help(self, checkerref=False):
"""return the help string for the given message id"""
desc = self.descr
if checkerref:
desc += " This message belongs to the %s checker." % self.checker.name
title = self.msg
if self.symbol:
msgid = "%s (%s)" % (sel... |
process a module | def process_module(self, node):
"""process a module
the module's content is accessible via node.stream() function
"""
with node.stream() as stream:
for (lineno, line) in enumerate(stream):
if line.rstrip().endswith("\\"):
self.add_message(... |
Extracts the environment PYTHONPATH and appends the current sys. path to those. | def _get_env():
"""Extracts the environment PYTHONPATH and appends the current sys.path to
those."""
env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(sys.path)
return env |
Pylint the given file. | def lint(filename, options=()):
"""Pylint the given file.
When run from emacs we will be in the directory of a file, and passed its
filename. If this file is part of a package and is trying to import other
modules from within its own package or another package rooted in a directory
below it, pylin... |
Run pylint from python | def py_run(command_options="", return_std=False, stdout=None, stderr=None):
"""Run pylint from python
``command_options`` is a string containing ``pylint`` command line options;
``return_std`` (boolean) indicates return of created standard output
and error (see below);
``stdout`` and ``stderr`` are... |
Transforms/ some/ path/ foo. png into (/ some/ path foo. png png ). | def target_info_from_filename(filename):
"""Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png')."""
basename = osp.basename(filename)
storedir = osp.dirname(osp.abspath(filename))
target = filename.split(".")[-1]
return storedir, basename, target |
given a dictionary representing an ordered graph ( i. e. key are vertices and values is a list of destination vertices representing edges ) return a list of detected cycles | def get_cycles(graph_dict, vertices=None):
"""given a dictionary representing an ordered graph (i.e. key are vertices
and values is a list of destination vertices representing edges), return a
list of detected cycles
"""
if not graph_dict:
return ()
result = []
if vertices is None:
... |
recursive function doing the real work for get_cycles | def _get_cycles(graph_dict, path, visited, result, vertice):
"""recursive function doing the real work for get_cycles"""
if vertice in path:
cycle = [vertice]
for node in path[::-1]:
if node == vertice:
break
cycle.insert(0, node)
# make a canonica... |
returns self. _source | def get_source(self):
"""returns self._source"""
if self._source is None:
self.emit("}\n")
self._source = "\n".join(self.lines)
del self.lines
return self._source |
Generates a graph file. | def generate(self, outputfile=None, dotfile=None, mapfile=None):
"""Generates a graph file.
:param str outputfile: filename and path [defaults to graphname.png]
:param str dotfile: filename and path [defaults to graphname.dot]
:param str mapfile: filename and path
:rtype: str
... |
emit an edge from <name1 > to <name2 >. edge properties: see http:// www. graphviz. org/ doc/ info/ attrs. html | def emit_edge(self, name1, name2, **props):
"""emit an edge from <name1> to <name2>.
edge properties: see http://www.graphviz.org/doc/info/attrs.html
"""
attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
n_from, n_to = normalize_node_id(name1), normalize_node_i... |
emit a node with given properties. node properties: see http:// www. graphviz. org/ doc/ info/ attrs. html | def emit_node(self, name, **props):
"""emit a node with given properties.
node properties: see http://www.graphviz.org/doc/info/attrs.html
"""
attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
self.emit("%s [%s];" % (normalize_node_id(name), ", ".join(sorted(at... |
calculate percentage of code/ doc/ comment/ empty | def report_raw_stats(sect, stats, _):
"""calculate percentage of code / doc / comment / empty
"""
total_lines = stats["total_lines"]
if not total_lines:
raise EmptyReportError()
sect.description = "%s lines have been analyzed" % total_lines
lines = ("type", "number", "%", "previous", "di... |
return the line type: docstring comment code empty | def get_type(tokens, start_index):
"""return the line type : docstring, comment, code, empty"""
i = start_index
tok_type = tokens[i][0]
start = tokens[i][2]
pos = start
line_type = None
while i < len(tokens) and tokens[i][2][0] == start[0]:
tok_type = tokens[i][0]
pos = token... |
init statistics | def open(self):
"""init statistics"""
self.stats = self.linter.add_stats(
total_lines=0,
code_lines=0,
empty_lines=0,
docstring_lines=0,
comment_lines=0,
) |
update stats | def process_tokens(self, tokens):
"""update stats"""
i = 0
tokens = list(tokens)
while i < len(tokens):
i, lines_number, line_type = get_type(tokens, i)
self.stats["total_lines"] += lines_number
self.stats[line_type] += lines_number |
format an options section using as ReST formatted output | def _rest_format_section(stream, section, options, doc=None):
"""format an options section using as ReST formatted output"""
if section:
print("%s\n%s" % (section, "'" * len(section)), file=stream)
if doc:
print(normalize_text(doc, line_len=79, indent=""), file=stream)
print(file=str... |
If the msgid is a numeric one then register it to inform the user it could furnish instead a symbolic msgid. | def _register_by_id_managed_msg(self, msgid, line, is_disabled=True):
"""If the msgid is a numeric one, then register it to inform the user
it could furnish instead a symbolic msgid."""
try:
message_definitions = self.msgs_store.get_message_definitions(msgid)
for message_... |
don t output message of the given id | def disable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""don't output message of the given id"""
self._set_msg_status(
msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line) |
reenable message of the given id | def enable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""reenable message of the given id"""
self._set_msg_status(
msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line, is_disabled=False) |
Get the message symbol of the given message id | def _message_symbol(self, msgid):
"""Get the message symbol of the given message id
Return the original message id if the message does not
exist.
"""
try:
return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)]
except UnknownMessageError:
... |
Returns the scope at which a message was enabled/ disabled. | def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
"""Returns the scope at which a message was enabled/disabled."""
if self.config.confidence and confidence.name not in self.config.confidence:
return MSG_STATE_CONFIDENCE
try:
if line in self.file_s... |
return true if the message associated to the given message id is enabled | def is_message_enabled(self, msg_descr, line=None, confidence=None):
"""return true if the message associated to the given message id is
enabled
msgid may be either a numeric or symbolic message id.
"""
if self.config.confidence and confidence:
if confidence.name not... |
Adds a message given by ID or name. | def add_message(
self,
msg_descr,
line=None,
node=None,
args=None,
confidence=UNDEFINED,
col_offset=None,
):
"""Adds a message given by ID or name.
If provided, the message string is expanded using args.
AST checkers must provide the ... |
output a full documentation in ReST format | def print_full_documentation(self, stream=None):
"""output a full documentation in ReST format"""
if not stream:
stream = sys.stdout
print("Pylint global options and switches", file=stream)
print("----------------------------------", file=stream)
print("", file=strea... |
Helper method for print_full_documentation. | def _print_checker_doc(checker_name, info, stream=None):
"""Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py.
"""
if not stream:
stream = sys.stdout
doc = info.get("doc")
module = info.get("module")
msgs = info.g... |
Return the length of the indentation on the given token s line. | def _get_indent_length(line):
"""Return the length of the indentation on the given token's line."""
result = 0
for char in line:
if char == " ":
result += 1
elif char == "\t":
result += _TAB_LENGTH
else:
break
return result |
Return a line with |s for each of the positions in the given lists. | def _get_indent_hint_line(bar_positions, bad_position):
"""Return a line with |s for each of the positions in the given lists."""
if not bar_positions:
return ("", "")
# TODO tabs should not be replaced by some random (8) number of spaces
bar_positions = [_get_indent_length(indent) for indent in... |
Get an indentation string for hanging indentation consisting of the line - indent plus a number of spaces to fill up to the column of this token. | def token_indent(self, idx):
"""Get an indentation string for hanging indentation, consisting of the line-indent plus
a number of spaces to fill up to the column of this token.
e.g. the token indent for foo
in "<TAB><TAB>print(foo)"
is "<TAB><TAB> "
"""
line... |
Record the first non - junk token at the start of a line. | def handle_line_start(self, pos):
"""Record the first non-junk token at the start of a line."""
if self._line_start > -1:
return
check_token_position = pos
if self._tokens.token(pos) == _ASYNC_TOKEN:
check_token_position += 1
self._is_block_opener = (
... |
Returns the valid offsets for the token at the given position. | def get_valid_indentations(self, idx):
"""Returns the valid offsets for the token at the given position."""
# The closing brace on a dict or the 'for' in a dict comprehension may
# reset two indent levels because the dict value is ended implicitly
stack_top = -1
if (
... |
Extracts indentation information for a hanging indent | def _hanging_indent_after_bracket(self, bracket, position):
"""Extracts indentation information for a hanging indent
Case of hanging indent after a bracket (including parenthesis)
:param str bracket: bracket in question
:param int position: Position of bracket in self._tokens
... |
Extracts indentation information for a continued indent. | def _continuation_inside_bracket(self, bracket, position):
"""Extracts indentation information for a continued indent."""
indentation = self._tokens.line_indent(position)
token_indent = self._tokens.token_indent(position)
next_token_indent = self._tokens.token_indent(position + 1)
... |
Pushes a new token for continued indentation on the stack. | def push_token(self, token, position):
"""Pushes a new token for continued indentation on the stack.
Tokens that can modify continued indentation offsets are:
* opening brackets
* 'lambda'
* : inside dictionaries
push_token relies on the caller to filter out those... |
a new line has been encountered process it if necessary | def new_line(self, tokens, line_end, line_start):
"""a new line has been encountered, process it if necessary"""
if _last_token_on_line_is(tokens, line_end, ";"):
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
line_num = tokens.start_line(line_start)
... |
Check that there are not unnecessary parens after a keyword. | def _check_keyword_parentheses(self, tokens, start):
"""Check that there are not unnecessary parens after a keyword.
Parens are unnecessary if there is exactly one balanced outer pair on a
line, and it is followed by a colon, and contains no commas (i.e. is not a
tuple).
Args:
... |
Extended check of PEP - 484 type hint presence | def _has_valid_type_annotation(self, tokens, i):
"""Extended check of PEP-484 type hint presence"""
if not self._inside_brackets("("):
return False
# token_info
# type string start end line
# 0 1 2 3 4
bracket_level = 0
for token in tok... |
Check the spacing of a single equals sign. | def _check_equals_spacing(self, tokens, i):
"""Check the spacing of a single equals sign."""
if self._has_valid_type_annotation(tokens, i):
self._check_space(tokens, i, (_MUST, _MUST))
elif self._inside_brackets("(") or self._inside_brackets("lambda"):
self._check_space(t... |
Check that a binary operator is surrounded by exactly one space. | def _check_surrounded_by_space(self, tokens, i):
"""Check that a binary operator is surrounded by exactly one space."""
self._check_space(tokens, i, (_MUST, _MUST)) |
process tokens and search for: | def process_tokens(self, tokens):
"""process tokens and search for :
_ non strict indentation (i.e. not always using the <indent> parameter as
indent unit)
_ too long lines (i.e. longer than <max_chars>)
_ optionally bad construct (if given, bad_construct must be a compile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.