INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Sends a payload object ( the result of calling _build_payload () + _serialize_payload () ). Uses the configured handler from SETTINGS [ handler ]
def send_payload(payload, access_token): """ Sends a payload object, (the result of calling _build_payload() + _serialize_payload()). Uses the configured handler from SETTINGS['handler'] Available handlers: - 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it ...
Searches a project for items that match the input criteria.
def search_items(title, return_fields=None, access_token=None, endpoint=None, **search_fields): """ Searches a project for items that match the input criteria. title: all or part of the item's title to search for. return_fields: the fields that should be returned for each item. e.g. ['id', ...
Creates. rollbar log file for use with rollbar - agent
def _create_agent_log(): """ Creates .rollbar log file for use with rollbar-agent """ log_file = SETTINGS['agent.log_file'] if not log_file.endswith('.rollbar'): log.error("Provided agent log file does not end with .rollbar, which it must. " "Using default instead.") ...
Called by report_exc_info () wrapper
def _report_exc_info(exc_info, request, extra_data, payload_data, level=None): """ Called by report_exc_info() wrapper """ if not _check_config(): return filtered_level = _filtered_level(exc_info[1]) if level is None: level = filtered_level filtered_exc_info = events.on_ex...
Called by report_message () wrapper
def _report_message(message, level, request, extra_data, payload_data): """ Called by report_message() wrapper """ if not _check_config(): return filtered_message = events.on_message(message, request=request, ...
Returns a dictionary describing the logged - in user using data from request.
def _build_person_data(request): """ Returns a dictionary describing the logged-in user using data from `request. Try request.rollbar_person first, then 'user', then 'user_id' """ if hasattr(request, 'rollbar_person'): rollbar_person_prop = request.rollbar_person try: pe...
Attempts to add information from the lambda context if it exists
def _add_lambda_context_data(data): """ Attempts to add information from the lambda context if it exists """ global _CURRENT_LAMBDA_CONTEXT context = _CURRENT_LAMBDA_CONTEXT if context is None: return try: lambda_data = { 'lambda': { 'remaining_tim...
Attempts to build request data ; if successful sets the request key on data.
def _add_request_data(data, request): """ Attempts to build request data; if successful, sets the 'request' key on `data`. """ try: request_data = _build_request_data(request) except Exception as e: log.exception("Exception while building request_data for Rollbar payload: %r", e) ...
Returns True if we should record local variables for the given frame.
def _check_add_locals(frame, frame_num, total_frames): """ Returns True if we should record local variables for the given frame. """ # Include the last frames locals # Include any frame locals that came from a file in the project's root return any(((frame_num == total_frames - 1), ...
Returns a dictionary containing data from the request. Can handle webob or werkzeug - based request objects.
def _build_request_data(request): """ Returns a dictionary containing data from the request. Can handle webob or werkzeug-based request objects. """ # webob (pyramid) if WebobBaseRequest and isinstance(request, WebobBaseRequest): return _build_webob_request_data(request) # django ...
Returns a dictionary containing information about the server environment.
def _build_server_data(): """ Returns a dictionary containing information about the server environment. """ # server environment server_data = { 'host': socket.gethostname(), 'pid': os.getpid() } # argv does not always exist in embedded python environments argv = getattr...
Returns the full payload as a string.
def _build_payload(data): """ Returns the full payload as a string. """ for k, v in iteritems(data): data[k] = _transform(v, key=(k,)) payload = { 'access_token': SETTINGS['access_token'], 'data': data } return payload
This runs the protocol on port 8000
def main(): rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted') """This runs the protocol on port 8000""" factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
This function returns a Hangul letter by composing the specified chosung joongsung and jongsung.
def compose(chosung, joongsung, jongsung=u''): """This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung. @param chosung @param joongsung @param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung.""" if jongsung is None: jo...
This function returns letters by decomposing the specified Hangul letter.
def decompose(hangul_letter): """This function returns letters by decomposing the specified Hangul letter.""" from . import checker if len(hangul_letter) < 1: raise NotLetterException('') elif not checker.is_hangul(hangul_letter): raise NotHangulException('') if hangul_letter in C...
Check whether this letter contains Jongsung
def has_jongsung(letter): """Check whether this letter contains Jongsung""" if len(letter) != 1: raise Exception('The target string must be one letter.') if not is_hangul(letter): raise NotHangulException('The target string must be Hangul') code = lt.hangul_index(letter) return code...
add josa at the end of this word
def attach(word, josa=EUN_NEUN): """add josa at the end of this word""" last_letter = word.strip()[-1] try: _, _, letter_jong = letter.decompose(last_letter) except NotHangulException: letter_jong = letter.get_substituent_of(last_letter) if letter_jong in ('', josa['except']): ...
Returns true if node is inside the name of an except handler.
def is_inside_except(node): """Returns true if node is inside the name of an except handler.""" current = node while current and not isinstance(current.parent, astroid.ExceptHandler): current = current.parent return current and current is current.parent.name
Return true if given node is inside lambda
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool: """Return true if given node is inside lambda""" parent = node.parent while parent is not None: if isinstance(parent, astroid.Lambda): return True parent = parent.parent return False
Recursively returns all atoms in nested lists and tuples.
def get_all_elements( node: astroid.node_classes.NodeNG ) -> Iterable[astroid.node_classes.NodeNG]: """Recursively returns all atoms in nested lists and tuples.""" if isinstance(node, (astroid.Tuple, astroid.List)): for child in node.elts: for e in get_all_elements(child): ...
Checks if an assignment node in an except handler clobbers an existing variable.
def clobber_in_except( node: astroid.node_classes.NodeNG ) -> Tuple[bool, Tuple[str, str]]: """Checks if an assignment node in an except handler clobbers an existing variable. Returns (True, args for W0623) if assignment clobbers an existing variable, (False, None) otherwise. """ if isinsta...
return True if the node is referencing the super builtin function
def is_super(node: astroid.node_classes.NodeNG) -> bool: """return True if the node is referencing the "super" builtin function """ if getattr(node, "name", None) == "super" and node.root().name == BUILTINS_NAME: return True return False
return true if the function does nothing but raising an exception
def is_error(node: astroid.node_classes.NodeNG) -> bool: """return true if the function does nothing but raising an exception""" for child_node in node.get_children(): if isinstance(child_node, astroid.Raise): return True return False
Returns True if the given node is an object from the __builtin__ module.
def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool: """Returns True if the given node is an object from the __builtin__ module.""" return node and node.root().name == BUILTINS_NAME
return True if the variable node is defined by a parent node ( list set dict or generator comprehension lambda ) or in a previous sibling node on the same line ( statement_defining ; statement_using )
def is_defined_before(var_node: astroid.node_classes.NodeNG) -> bool: """return True if the variable node is defined by a parent node (list, set, dict, or generator comprehension, lambda) or in a previous sibling node on the same line (statement_defining ; statement_using) """ varname = var_node.nam...
return true if the given Name node is used in function or lambda default argument s value
def is_default_argument(node: astroid.node_classes.NodeNG) -> bool: """return true if the given Name node is used in function or lambda default argument's value """ parent = node.scope() if isinstance(parent, (astroid.FunctionDef, astroid.Lambda)): for default_node in parent.args.defaults: ...
return true if the name is used in function decorator
def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool: """return true if the name is used in function decorator""" parent = node.parent while parent is not None: if isinstance(parent, astroid.Decorators): return True if parent.is_statement or isinstance( pa...
return True if frame is an astroid. Class node with node in the subtree of its bases attribute
def is_ancestor_name( frame: astroid.node_classes.NodeNG, node: astroid.node_classes.NodeNG ) -> bool: """return True if `frame` is an astroid.Class node with `node` in the subtree of its bases attribute """ try: bases = frame.bases except AttributeError: return False for bas...
return the higher parent which is not an AssignName Tuple or List node
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG: """return the higher parent which is not an AssignName, Tuple or List node """ while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)): node = node.parent return node
return True if <name > is a method overridden from an ancestor
def overrides_a_method(class_node: astroid.node_classes.NodeNG, name: str) -> bool: """return True if <name> is a method overridden from an ancestor""" for ancestor in class_node.ancestors(): if name in ancestor and isinstance(ancestor[name], astroid.FunctionDef): return True return Fals...
decorator to store messages that are handled by a checker method
def check_messages(*messages: str) -> Callable: """decorator to store messages that are handled by a checker method""" def store_messages(func): func.checks_msgs = messages return func return store_messages
Parses a format string returning a tuple of ( keys num_args ) where keys is the set of mapping keys in the format string and num_args is the number of arguments required by the format string. Raises IncompleteFormatString or UnsupportedFormatCharacter if a parse error occurs.
def parse_format_string( format_string: str ) -> Tuple[Set[str], int, Dict[str, str], List[str]]: """Parses a format string, returning a tuple of (keys, num_args), where keys is the set of mapping keys in the format string, and num_args is the number of arguments required by the format string. Raises ...
Given a format string return an iterator of all the valid format fields. It handles nested fields as well.
def collect_string_fields(format_string) -> Iterable[Optional[str]]: """ Given a format string, return an iterator of all the valid format fields. It handles nested fields as well. """ formatter = string.Formatter() try: parseiterator = formatter.parse(format_string) for result i...
Parses a PEP 3101 format string returning a tuple of ( keyword_arguments implicit_pos_args_cnt explicit_pos_args ) where keyword_arguments is the set of mapping keys in the format string implicit_pos_args_cnt is the number of arguments required by the format string and explicit_pos_args is the number of arguments passe...
def parse_format_method_string( format_string: str ) -> Tuple[List[Tuple[str, List[Tuple[bool, str]]]], int, int]: """ Parses a PEP 3101 format string, returning a tuple of (keyword_arguments, implicit_pos_args_cnt, explicit_pos_args), where keyword_arguments is the set of mapping keys in the format...
return True if attribute name is protected ( start with _ and some other details ) False otherwise.
def is_attr_protected(attrname: str) -> bool: """return True if attribute name is protected (start with _ and some other details), False otherwise. """ return ( attrname[0] == "_" and attrname != "_" and not (attrname.startswith("__") and attrname.endswith("__")) )
return klass node for a method node ( or a staticmethod or a classmethod ) return null otherwise
def node_frame_class( node: astroid.node_classes.NodeNG ) -> Optional[astroid.node_classes.NodeNG]: """return klass node for a method node (or a staticmethod or a classmethod), return null otherwise """ klass = node.frame() while klass is not None and not isinstance(klass, astroid.ClassDef): ...
Check that attribute name is private ( at least two leading underscores at most one trailing underscore )
def is_attr_private(attrname: str) -> Optional[Match[str]]: """Check that attribute name is private (at least two leading underscores, at most one trailing underscore) """ regex = re.compile("^_{2,}.*[^_]+_?$") return regex.match(attrname)
Returns the specified argument from a function call.
def get_argument_from_call( call_node: astroid.Call, position: int = None, keyword: str = None ) -> astroid.Name: """Returns the specified argument from a function call. :param astroid.Call call_node: Node representing a function call to check. :param int position: position of the argument. :param ...
Return true if the given class node is subclass of exceptions. Exception.
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool: """ Return true if the given class node is subclass of exceptions.Exception. """ ancestors = node.ancestors() if hasattr(node, "ancestors") else [] for ancestor in itertools.chain([node], ancestors): if ( anc...
Check if the given exception handler catches the given error_type.
def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool: """ Check if the given exception handler catches the given error_type. The *handler* parameter is a node, representing an ExceptHandler node. The *error_type* can be an exception, such as AttributeError, the name of an excep...
Detect if the given function node is decorated with a property.
def decorated_with_property(node: astroid.FunctionDef) -> bool: """ Detect if the given function node is decorated with a property. """ if not node.decorators: return False for decorator in node.decorators.nodes: if not isinstance(decorator, astroid.Name): continue try: ...
Determine if the func node has a decorator with the qualified name qname.
def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool: """Determine if the `func` node has a decorator with the qualified name `qname`.""" decorators = func.decorators.nodes if func.decorators else [] for decorator_node in decorators: try: if any( i...
Get the unimplemented abstract methods for the given * node *.
def unimplemented_abstract_methods( node: astroid.node_classes.NodeNG, is_abstract_cb: astroid.FunctionDef = None ) -> Dict[str, astroid.node_classes.NodeNG]: """ Get the unimplemented abstract methods for the given *node*. A method can be considered abstract if the callback *is_abstract_cb* return...
Return the ExceptHandler or the TryExcept node in which the node is.
def find_try_except_wrapper_node( node: astroid.node_classes.NodeNG ) -> Union[astroid.ExceptHandler, astroid.TryExcept]: """Return the ExceptHandler or the TryExcept node in which the node is.""" current = node ignores = (astroid.ExceptHandler, astroid.TryExcept) while current and not isinstance(cu...
Check if the given node is from a fallback import block.
def is_from_fallback_block(node: astroid.node_classes.NodeNG) -> bool: """Check if the given node is from a fallback import block.""" context = find_try_except_wrapper_node(node) if not context: return False if isinstance(context, astroid.ExceptHandler): other_body = context.parent.body...
Return the collections of handlers handling the exception in arguments.
def get_exception_handlers( node: astroid.node_classes.NodeNG, exception=Exception ) -> List[astroid.ExceptHandler]: """Return the collections of handlers handling the exception in arguments. Args: node (astroid.NodeNG): A node that is potentially wrapped in a try except. exception (builtin...
Check if the node is directly under a Try/ Except statement. ( but not under an ExceptHandler! )
def is_node_inside_try_except(node: astroid.Raise) -> bool: """Check if the node is directly under a Try/Except statement. (but not under an ExceptHandler!) Args: node (astroid.Raise): the node raising the exception. Returns: bool: True if the node is inside a try/except statement, Fal...
Check if the node is in a TryExcept which handles the given exception.
def node_ignores_exception( node: astroid.node_classes.NodeNG, exception=Exception ) -> bool: """Check if the node is in a TryExcept which handles the given exception. If the exception is not given, the function is going to look for bare excepts. """ managing_handlers = get_exception_handlers(n...
return true if the given class node should be considered as an abstract class
def class_is_abstract(node: astroid.ClassDef) -> bool: """return true if the given class node should be considered as an abstract class """ for method in node.methods(): if method.parent.frame() is node: if method.is_abstract(pass_is_abstract=False): return True r...
Return the inferred value for the given node.
def safe_infer( node: astroid.node_classes.NodeNG, context=None ) -> Optional[astroid.node_classes.NodeNG]: """Return the inferred value for the given node. Return None if inference failed or if there is some ambiguity (more than one node has been inferred). """ try: inferit = node.infe...
Return the inferred type for node
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]: """Return the inferred type for `node` If there is more than one possible type, or if inferred type is Uninferable or None, return None """ # check there is only one possible type for the assign node. Else we # don't handle it ...
Check if the given function node is a singledispatch function.
def is_registered_in_singledispatch_function(node: astroid.FunctionDef) -> bool: """Check if the given function node is a singledispatch function.""" singledispatch_qnames = ( "functools.singledispatch", "singledispatch.singledispatch", ) if not isinstance(node, astroid.FunctionDef): ...
Get the last lineno of the given node. For a simple statement this will just be node. lineno but for a node that has child statements ( e. g. a method ) this will be the lineno of the last child statement recursively.
def get_node_last_lineno(node: astroid.node_classes.NodeNG) -> int: """ Get the last lineno of the given node. For a simple statement this will just be node.lineno, but for a node that has child statements (e.g. a method) this will be the lineno of the last child statement recursively. """ # 'fi...
Check if the postponed evaluation of annotations is enabled
def is_postponed_evaluation_enabled(node: astroid.node_classes.NodeNG) -> bool: """Check if the postponed evaluation of annotations is enabled""" name = "annotations" module = node.root() stmt = module.locals.get(name) return ( stmt and isinstance(stmt[0], astroid.ImportFrom) ...
Check if first node is a subclass of second node.: param child: Node to check for subclass.: param parent: Node to check for superclass.: returns: True if child is derived from parent. False otherwise.
def is_subclass_of(child: astroid.ClassDef, parent: astroid.ClassDef) -> bool: """ Check if first node is a subclass of second node. :param child: Node to check for subclass. :param parent: Node to check for superclass. :returns: True if child is derived from parent. False otherwise. """ if ...
Split the names of the given module into subparts
def _qualified_names(modname): """Split the names of the given module into subparts For example, _qualified_names('pylint.checkers.ImportsChecker') returns ['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker'] """ names = modname.split(".") return [".".join(names[0 : i...
Get a prepared module name from the given import node
def _get_import_name(importnode, modname): """Get a prepared module name from the given import node In the case of relative imports, this will return the absolute qualified module name, which might be useful for debugging. Otherwise, the initial module name is returned unchanged. """ if isi...
return the node where [ base. ] <name > is imported or None if not found
def _get_first_import(node, context, name, base, level, alias): """return the node where [base.]<name> is imported or None if not found """ fullname = "%s.%s" % (base, name) if base else name first = None found = False for first in context.body: if first is node: continue ...
get a list of 2 - uple ( module list_of_files_which_import_this_module ) it will return a dictionary to represent this as a tree
def _make_tree_defs(mod_files_list): """get a list of 2-uple (module, list_of_files_which_import_this_module), it will return a dictionary to represent this as a tree """ tree_defs = {} for mod, files in mod_files_list: node = (tree_defs, ()) for prefix in mod.split("."): ...
return a string which represents imports as a tree
def _repr_tree_defs(data, indent_str=None): """return a string which represents imports as a tree""" lines = [] nodes = data.items() for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[0])): if not files: files = "" else: files = "(%s)" % ",".joi...
write dependencies as a dot ( graphviz ) file
def _dependencies_graph(filename, dep_info): """write dependencies as a dot (graphviz) file """ done = {} printer = DotBackend(filename[:-4], rankdir="LR") printer.emit('URL="." node[shape="box"]') for modname, dependencies in sorted(dep_info.items()): done[modname] = 1 printer.e...
generate a dependencies graph and add some information about it in the report s section
def _make_graph(filename, dep_info, sect, gtype): """generate a dependencies graph and add some information about it in the report's section """ _dependencies_graph(filename, dep_info) sect.append(Paragraph("%simports graph has been written to %s" % (gtype, filename)))
called before visiting project ( i. e set of modules )
def open(self): """called before visiting project (i.e set of modules)""" self.linter.add_stats(dependencies={}) self.linter.add_stats(cycles=[]) self.stats = self.linter.stats self.import_graph = collections.defaultdict(set) self._module_pkg = {} # mapping of modules to...
called before visiting project ( i. e set of modules )
def close(self): """called before visiting project (i.e set of modules)""" 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): ...
triggered when an import statement is seen
def visit_import(self, node): """triggered when an import statement is seen""" self._check_reimport(node) self._check_import_as_rename(node) modnode = node.root() names = [name for name, _ in node.names] if len(names) >= 2: self.add_message("multiple-imports"...
triggered when a from statement is seen
def visit_importfrom(self, node): """triggered when a from statement is seen""" basename = node.modname imported_module = self._get_imported_module(node, basename) self._check_import_as_rename(node) self._check_misplaced_future(node) self._check_deprecated_module(node, b...
Check node import or importfrom node position is correct
def _check_position(self, node): """Check `node` import or importfrom node position is correct Send a message if `node` comes before another instruction """ # if a first non-import instruction has already been encountered, # it means the import comes after it and therefore is n...
Record the package node imports from
def _record_import(self, node, importedmodnode): """Record the package `node` imports from""" if isinstance(node, astroid.ImportFrom): importedname = node.modname else: importedname = importedmodnode.name if importedmodnode else None if not importedname: ...
Checks imports of module node are grouped by category
def _check_imports_order(self, _module_node): """Checks imports of module `node` are grouped by category Imports must follow this order: standard, 3rd party, local """ std_imports = [] third_party_imports = [] first_party_imports = [] # need of a list that holds ...
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 ): """check relative import. node is either an Import or From node, modname the imported module name. """ if not self.linter.is_message_enabled("relative-import"): return None ...
notify an imported module used to analyze dependencies
def _add_imported_module(self, node, importedmodname): """notify an imported module, used to analyze dependencies""" module_file = node.root().file context_name = node.root().name base = os.path.splitext(os.path.basename(module_file))[0] try: importedmodname = astroi...
check if the module is deprecated
def _check_deprecated_module(self, node, mod_path): """check if the module is deprecated""" 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 module has a preferred replacement
def _check_preferred_module(self, node, mod_path): """check if the module has a preferred replacement""" if mod_path in self.preferred_modules: self.add_message( "preferred-module", node=node, args=(self.preferred_modules[mod_path], mod_path), ...
check if the import is necessary ( i. e. not already done )
def _check_reimport(self, node, basename=None, level=None): """check if the import is necessary (i.e. not already done)""" if not self.linter.is_message_enabled("reimported"): return frame = node.frame() root = node.root() contexts = [(frame, level)] if root ...
return a verbatim layout for displaying dependencies
def _report_external_dependencies(self, sect, _, _dummy): """return a verbatim layout for displaying dependencies""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) s...
write dependencies as a dot ( graphviz ) file
def _report_dependencies_graph(self, sect, _, _dummy): """write dependencies as a dot (graphviz) file""" 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 ...
build the internal or the external depedency graph
def _filter_dependencies_graph(self, internal): """build the internal or the external depedency graph""" graph = collections.defaultdict(set) for importee, importers in self.stats["dependencies"].items(): for importer in importers: package = self._module_pkg.get(impor...
Read config file and return list of options
def get_default_options(): """ Read config file and return list of options """ options = [] home = os.environ.get("HOME", "") if home: rcfile = os.path.join(home, RCFILE) try: options = open(rcfile).read().split() except IOError: pass # ignore if ...
insert default options to sys. argv
def insert_default_options(): """insert default options to sys.argv """ options = get_default_options() options.reverse() for arg in options: sys.argv.insert(1, arg)
return the visibility from a name: public protected private or special
def get_visibility(name): """return the visibility from a name: public, protected, private or special """ if SPECIAL.match(name): visibility = "special" elif PRIVATE.match(name): visibility = "private" elif PROTECTED.match(name): visibility = "protected" else: vi...
return true if the node should be treated
def show_attr(self, node): """return true if the node should be treated """ visibility = get_visibility(getattr(node, "name", node)) return not self.__mode & VIS_MOD[visibility]
walk on the tree from <node > getting callbacks from handler
def walk(self, node, _done=None): """walk on the tree from <node>, getting callbacks from handler""" if _done is None: _done = set() if node in _done: raise AssertionError((id(node), node, node.parent)) _done.add(node) self.visit(node) for child_no...
get callbacks from handler for the visited node
def get_callbacks(self, node): """get callbacks from handler for the visited node""" klass = node.__class__ methods = self._cache.get(klass) if methods is None: handler = self.handler kid = klass.__name__.lower() e_method = getattr( han...
walk on the tree from <node > getting callbacks from handler
def visit(self, node): """walk on the tree from <node>, getting callbacks from handler""" method = self.get_callbacks(node)[0] if method is not None: method(node)
walk on the tree from <node > getting callbacks from handler
def leave(self, node): """walk on the tree from <node>, getting callbacks from handler""" method = self.get_callbacks(node)[1] if method is not None: method(node)
launch the visit starting from the given node
def visit(self, node): """launch the visit starting from the given node""" if node in self._visited: return None self._visited[node] = 1 # FIXME: use set ? methods = self.get_callbacks(node) if methods[0] is not None: methods[0](node) if hasattr(n...
Check the consistency of msgid.
def check_consistency(self) -> None: """Check the consistency of msgid. msg ids for a checker should be a string of len 4, where the two first characters are the checker id and the two last the msg id in this checker. :raises InvalidMessageError: If the checker id in the messag...
Visit a Call node.
def visit_call(self, node): """Visit a Call node.""" try: for inferred in node.func.infer(): if inferred is astroid.Uninferable: continue elif inferred.root().name == OPEN_MODULE: if getattr(node.func, "name", None) in O...
Check that a datetime was infered. If so emit boolean - datetime warning.
def _check_datetime(self, node): """ Check that a datetime was infered. If so, emit boolean-datetime warning. """ try: infered = next(node.infer()) except astroid.InferenceError: return if isinstance(infered, Instance) and infered.qname() == "datet...
Check that the mode argument of an open or file call is valid.
def _check_open_mode(self, node): """Check that the mode argument of an open or file call is valid.""" try: mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode") except utils.NoSuchArgumentError: return if mode_arg: mode_arg = utils...
Manage message of different type and in the context of path.
def handle_message(self, msg): """Manage message of different type and in the context of path.""" self.messages.append( { "type": msg.category, "module": msg.module, "obj": msg.obj, "line": msg.line, "column": ms...
Launch layouts display
def display_messages(self, layout): """Launch layouts display""" print(json.dumps(self.messages, indent=4), file=self.out)
get title for objects
def get_title(self, node): """get title for objects""" title = node.name if self.module_names: title = "%s.%s" % (node.root().name, title) return title
set different default options with _default dictionary
def _set_default_options(self): """set different default options with _default dictionary""" self.module_names = self._set_option(self.config.module_names) all_ancestors = self._set_option(self.config.all_ancestors) all_associated = self._set_option(self.config.all_associated) an...
true if builtins and not show_builtins
def show_node(self, node): """true if builtins and not show_builtins""" if self.config.show_builtin: return True return node.root().name != BUILTINS_NAME
visit one class and add it to diagram
def add_class(self, node): """visit one class and add it to diagram""" self.linker.visit(node) self.classdiagram.add_object(self.get_title(node), node)
return ancestor nodes of a class node
def get_ancestors(self, node, level): """return ancestor nodes of a class node""" if level == 0: return for ancestor in node.ancestors(recurs=False): if not self.show_node(ancestor): continue yield ancestor
return associated nodes of a class node
def get_associated(self, klass_node, level): """return associated nodes of a class node""" if level == 0: return for association_nodes in list(klass_node.instance_attrs_type.values()) + list( klass_node.locals_type.values() ): for node in association_n...
extract recursively classes related to klass_node
def extract_classes(self, klass_node, anc_level, association_level): """extract recursively classes related to klass_node""" if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node): return self.add_class(klass_node) for ancestor in self.get_ancestors(klas...
visit a pyreverse. utils. Project node
def visit_project(self, node): """visit a pyreverse.utils.Project node create a diagram definition for packages """ mode = self.config.mode if len(node.modules) > 1: self.pkgdiagram = PackageDiagram("packages %s" % node.name, mode) else: self.pkgd...