INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
List all the check groups that pylint knows about
def cb_list_groups(self, *args, **kwargs): """List all the check groups that pylint knows about These should be useful to know what check groups someone can disable or enable. """ for check in self.linter.get_checker_names(): print(check) sys.exit(0)
Wrap the text on the given line length.
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
return the module name and the frame id in the module
def get_module_and_frameid(node): """return the module name and the frame id in the module""" frame = node.frame() module, obj = "", [] while frame: if isinstance(frame, Module): module = frame.name else: obj.append(getattr(frame, "name", "<lambda>")) try:...
return decoded line from encoding or decode with default encoding
def safe_decode(line, encoding, *args, **kwargs): """return decoded line from encoding or decode with default encoding""" try: return line.decode(encoding or sys.getdefaultencoding(), *args, **kwargs) except LookupError: return line.decode(sys.getdefaultencoding(), *args, **kwargs)
Determines if the basename is matched in a regex blacklist
def _basename_in_blacklist_re(base_name, black_list_re): """Determines if the basename is matched in a regex blacklist :param str base_name: The basename of the file :param list black_list_re: A collection of regex patterns to match against. Successful matches are blacklisted. :returns: `True`...
take a list of files/ modules/ packages and return the list of tuple ( file module name ) which have to be actually checked
def expand_modules(files_or_modules, black_list, black_list_re): """take a list of files/modules/packages and return the list of tuple (file, module name) which have to be actually checked """ result = [] errors = [] for something in files_or_modules: if basename(something) in black_list...
load all module and package in the given directory looking for a register function in each one used to register pylint checkers
def register_plugins(linter, directory): """load all module and package in the given directory, looking for a 'register' function in each one, used to register pylint checkers """ imported = {} for filename in listdir(directory): base, extension = splitext(filename) if base in import...
Retrieve an option defined by the given * checker * or by all known option providers.
def get_global_option(checker, option, default=None): """ Retrieve an option defined by the given *checker* or by all known option providers. It will look in the list of all options providers until the given *option* will be found. If the option wasn't found, the *default* value will be returned. ...
return a list of stripped string by splitting the string given as argument on sep ( by default ). Empty string are discarded.
def _splitstrip(string, sep=","): """return a list of stripped string by splitting the string given as argument on `sep` (',' by default). Empty string are discarded. >>> _splitstrip('a, b, c , 4,,') ['a', 'b', 'c', '4'] >>> _splitstrip('a') ['a'] >>> _splitstrip('a,\nb,\nc,') ['a', ...
remove optional quotes ( simple or double ) from the string
def _unquote(string): """remove optional quotes (simple or double) from the string :type string: str or unicode :param string: an optionally quoted string :rtype: str or unicode :return: the unquoted string (or the input string if it wasn't quoted) """ if not string: return string ...
return string as a comment
def _comment(string): """return string as a comment""" lines = [line.strip() for line in string.splitlines()] return "# " + ("%s# " % linesep).join(lines)
return the user input s value from a compiled value
def _format_option_value(optdict, value): """return the user input's value from a 'compiled' value""" if isinstance(value, (list, tuple)): value = ",".join(_format_option_value(optdict, item) for item in value) elif isinstance(value, dict): value = ",".join("%s:%s" % (k, v) for k, v in value...
format an options section using the INI format
def format_section(stream, section, options, doc=None): """format an options section using the INI format""" if doc: print(_comment(doc), file=stream) print("[%s]" % section, file=stream) _ini_format(stream, options)
format options using the INI format
def _ini_format(stream, options): """format options using the INI format""" for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optdict.get("help") if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent="# ") ...
insert a child node
def insert(self, index, child): """insert a child node""" self.children.insert(index, child) child.parent = self
return the visit name for the mixed class. When calling accept the method < visit_ + name returned by this method > will be called on the visitor
def _get_visit_name(self): """ return the visit name for the mixed class. When calling 'accept', the method <'visit_' + name returned by this method> will be called on the visitor """ try: # pylint: disable=no-member return self.TYPE.replace("-", "...
overridden to detect problems easily
def append(self, child): """overridden to detect problems easily""" assert child not in self.parents() VNode.append(self, child)
return the ancestor nodes
def parents(self): """return the ancestor nodes""" assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
format and write the given layout into the stream object
def format(self, layout, stream=None, encoding=None): """format and write the given layout into the stream object unicode policy: unicode strings may be found in the layout; try to call stream.write with it, but give it back encoded using the given encoding if it fails """ ...
trick to get table content without actually writing it
def get_table_content(self, table): """trick to get table content without actually writing it return an aligned list of lists containing table cells values as string """ result = [[]] cols = table.cols for cell in self.compute_content(table): if cols == 0: ...
trick to compute the formatting of children layout before actually writing it
def compute_content(self, layout): """trick to compute the formatting of children layout before actually writing it return an iterator on strings (one for each child element) """ # Patch the underlying output stream with a fresh-generated stream, # which is used to store...
Walk the AST to collect block level options line numbers.
def collect_block_lines(self, msgs_store, module_node): """Walk the AST to collect block level options line numbers.""" for msg, lines in self._module_msgs_state.items(): self._raw_module_msgs_state[msg] = lines.copy() orig_state = self._module_msgs_state.copy() self._module_...
Recursively walk ( depth first ) AST to collect block level options line numbers.
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 ...
Set status ( enabled/ disable ) for a given message at a given line
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}
Report an ignored message.
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...
register a report
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...
disable the report of the given id
def enable_report(self, reportid): """disable the report of the given id""" reportid = reportid.upper() self._reports_state[reportid] = True
disable the report of the given id
def disable_report(self, reportid): """disable the report of the given id""" reportid = reportid.upper() self._reports_state[reportid] = False
render registered reports
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...
add some stats entries to the statistic dictionary raise an AssertionError if there is a key conflict
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 ...
Get the name of the property that the given node is a setter for.
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...
Get the property node for the given setter node.
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 ...
Check if a return node returns a value other than None.
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...
Gets all of the possible raised exception types for the given raise node.
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...
required method to auto register this checker
def register(linter): """required method to auto register this checker""" linter.register_checker(EncodingChecker(linter)) linter.register_checker(ByIdManagedMessagesChecker(linter))
inspect the source file to find messages activated or deactivated by id.
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: ...
inspect the source file to find encoding problem
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): ...
inspect the source to find fixme problems
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 =...
Check if the name is a future import from another module.
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,...
Returns True if stmt in inside the else branch for a parent For stmt.
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 )
get overridden method if any
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'...
return extra information to add to the message for unpacking - non - sequence and unbalanced - tuple - unpacking errors
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: ...
Detect that the given frames shares a global scope.
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 ...
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.
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...
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.
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...
Checks if name_node has corresponding assign statement in same scope
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)
Mark the name as consumed and delete it from the to_consume dictionary
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]
visit module: update consumption analysis variable checks globals doesn t overrides builtins
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...
leave module: check globals
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) ...
visit function: update consumption analysis variable and check locals
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...
leave function: check function s locals are consumed
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: ...
check names imported exists in the global scope
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 ...
Return True if the node is in a local class scope as an assignment.
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 ...
check that a name is defined if the current scope and doesn t redefine a built - in
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...
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
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 ...
check modules attribute accesses
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...
check modules attribute accesses
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...
Check unbalanced tuple unpacking for assignments and unpacking non - sequences as well as in case self/ cls get assigned.
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...
Check that self/ cls don t get assigned
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( ...
Check for unbalanced tuple unpacking and unpacking non sequences.
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:...
check that module_names ( list of string ) are accessible through the given module if the latest access name corresponds to a module return it
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...
Update consumption analysis for metaclasses.
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...
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
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...
Creates the proper script names required for each platform ( taken from 4Suite )
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
return a list of subpackages for the given directory
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: ...
setup entry point
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_...
overridden from install_lib class
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...
return lines with leading/ trailing whitespace and any ignored code features removed
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...
make a layout with some stats about duplication
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...
standalone command line access point
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...
append a file to search for similarities
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( ...
compute similarities in appended files
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...
display computed similarities on stdout
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: ...
find similarities in the two given linesets
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): ...
iterate on similarities among all files by making a cartesian product
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): ...
return an iterator on stripped lines starting from a given index if specified else 0
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...
create the index for this set
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
method called to set an option ( registered in the options list )
def set_option(self, optname, value, action=None, optdict=None): """method called to set an option (registered in the options list) overridden to report options setting to Similar """ BaseChecker.set_option(self, optname, value, action, optdict) if optname == "min-similarity-lin...
init the checkers: reset linesets and statistics information
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 )
process a module
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)
compute and display similarities on closing ( i. e. end of parsing )
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...
Check if a definition signature is equivalent to a call.
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...
Check equality of nodes based on the comparison of their attributes named attr_name.
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...
Check if original and overridden methods arguments have different default values
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...
Determine if the two methods have different parameters
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,...
Check if the func was called in any of the given methods belonging to the * klass *. Returns True if so False otherwise.
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 = ...
Check if the given attribute * name * is a property in the given * klass *.
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 ...
Safely infer the return value of a function.
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...
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
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_...
required method to auto register this checker
def register(linter): """required method to auto register this checker """ linter.register_checker(ClassChecker(linter)) linter.register_checker(SpecialMethodsChecker(linter))
Set the given node as accessed.
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)
init visit variable _accessed
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...
Detect that a class has a consistent mro or duplicate bases.
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_...
Detect that a class inherits something which is not a class or a type.
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...
close a class node: check that instance attributes are defined in __init__ and check access to existent members
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"...
check method arguments overriding
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...
Check if the given function node is an useless method override
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...
on method node check if this method couldn t be a function
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...
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 )
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...
Check that the given AssignAttr node is defined in the class slots.
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)...