當前位置: 首頁>>代碼示例>>Python>>正文


Python astroid.Import方法代碼示例

本文整理匯總了Python中astroid.Import方法的典型用法代碼示例。如果您正苦於以下問題:Python astroid.Import方法的具體用法?Python astroid.Import怎麽用?Python astroid.Import使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在astroid的用法示例。


在下文中一共展示了astroid.Import方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: is_from_fallback_block

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def is_from_fallback_block(node):
    """Check if the given node is from a fallback import block."""
    context = _import_node_context(node)
    if not context:
        return False

    if isinstance(context, astroid.ExceptHandler):
        other_body = context.parent.body
        handlers = context.parent.handlers
    else:
        other_body = itertools.chain.from_iterable(
            handler.body for handler in context.handlers)
        handlers = context.handlers

    has_fallback_imports = any(isinstance(import_node, (astroid.ImportFrom, astroid.Import))
                               for import_node in other_body)
    ignores_import_error = _except_handlers_ignores_exception(handlers, ImportError)
    return ignores_import_error or has_fallback_imports 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:20,代碼來源:utils.py

示例2: _find_frame_imports

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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 imports:
        for import_name, import_alias in import_node.names:
            # If the import uses an alias, check only that.
            # Otherwise, check only the import name.
            if import_alias:
                if import_alias == name:
                    return True
            elif import_name and import_name == name:
                return True
    return None 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:19,代碼來源:variables.py

示例3: visit_functiondef

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def visit_functiondef(self, node):
        if not self.linter.is_message_enabled('wrong-import-position', node.fromlineno):
            return
        # If it is the first non import instruction of the module, record it.
        if self._first_non_import_node:
            return

        # Check if the node belongs to an `If` or a `Try` block. If they
        # contain imports, skip recording this node.
        if not isinstance(node.parent.scope(), astroid.Module):
            return

        root = node
        while not isinstance(root.parent, astroid.Module):
            root = root.parent

        if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
            if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
                return

        self._first_non_import_node = node 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:23,代碼來源:imports.py

示例4: _check_relative_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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
        if importedmodnode.file is None:
            return False # built-in module
        if modnode is importedmodnode:
            return False # module importing itself
        if modnode.absolute_import_activated() or getattr(importnode, 'level', None):
            return False
        if importedmodnode.name != importedasname:
            # this must be a relative import...
            self.add_message('relative-import',
                             args=(importedasname, importedmodnode.name),
                             node=importnode)
            return None
        return None 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:22,代碼來源:imports.py

示例5: _get_assigns

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def _get_assigns(self, node: Union[astroid.FunctionDef, astroid.Module]) -> Set[str]:
        """Returns a set of all local and parameter variables that could be
        defined in the program (either a function or module).

        IF a variable 'v' is defined in a function and there is no global/nonlocal
        statement applied to 'v' THEN 'v' is a local variable.

        Note that `local variable` in the context of a module level analysis,
        refers to global variables.
        """
        assigns = set()
        kills = set()
        for name, nodes in node.scope().locals.items():
            if any(isinstance(elem, astroid.AssignName) for elem in nodes):
                assigns.add(name)
        for statement in node.nodes_of_class((astroid.Nonlocal, astroid.Global,
                                              astroid.ImportFrom, astroid.Import), astroid.FunctionDef):
            for name in statement.names:
                if type(name) is tuple:
                    # name[1] is the alias of the imported object/var name[0]
                    # name[1] == str or None
                    name = name[1] or name[0]
                kills.add(name)

        return assigns.difference(kills) 
開發者ID:pyta-uoft,項目名稱:pyta,代碼行數:27,代碼來源:possibly_undefined_checker.py

示例6: is_defined_before

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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.name
    _node = var_node.parent
    while _node:
        if is_defined_in_scope(var_node, varname, _node):
            return True
        _node = _node.parent
    # possibly multiple statements on the same line using semi colon separator
    stmt = var_node.statement()
    _node = stmt.previous_sibling()
    lineno = stmt.fromlineno
    while _node and _node.fromlineno == lineno:
        for assign_node in _node.nodes_of_class(astroid.AssignName):
            if assign_node.name == varname:
                return True
        for imp_node in _node.nodes_of_class((astroid.ImportFrom, astroid.Import)):
            if varname in [name[1] or name[0] for name in imp_node.names]:
                return True
        _node = _node.previous_sibling()
    return False 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:26,代碼來源:utils.py

示例7: is_from_fallback_block

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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
        handlers = context.parent.handlers
    else:
        other_body = itertools.chain.from_iterable(
            handler.body for handler in context.handlers
        )
        handlers = context.handlers

    has_fallback_imports = any(
        isinstance(import_node, (astroid.ImportFrom, astroid.Import))
        for import_node in other_body
    )
    ignores_import_error = _except_handlers_ignores_exception(handlers, ImportError)
    return ignores_import_error or has_fallback_imports 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:23,代碼來源:utils.py

示例8: _redefines_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def _redefines_import(node):
    """ Detect that the given node (AssignName) is inside an
    exception handler and redefines an import from the tryexcept body.
    Returns True if the node redefines an import, False otherwise.
    """
    current = node
    while current and not isinstance(current.parent, astroid.ExceptHandler):
        current = current.parent
    if not current or not utils.error_of_type(current.parent, ImportError):
        return False
    try_block = current.parent.parent
    for import_node in try_block.nodes_of_class((astroid.ImportFrom, astroid.Import)):
        for name, alias in import_node.names:
            if alias:
                if alias == node.name:
                    return True
            elif name == node.name:
                return True
    return False 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:21,代碼來源:base.py

示例9: _check_relative_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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
        if importedmodnode.file is None:
            return False  # built-in module
        if modnode is importedmodnode:
            return False  # module importing itself
        if modnode.absolute_import_activated() or getattr(importnode, "level", None):
            return False
        if importedmodnode.name != importedasname:
            # this must be a relative import...
            self.add_message(
                "relative-import",
                args=(importedasname, importedmodnode.name),
                node=importnode,
            )
            return None
        return None 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:25,代碼來源:imports.py

示例10: _has_locals_call_after_node

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def _has_locals_call_after_node(stmt, scope):
    skip_nodes = (
        astroid.FunctionDef,
        astroid.ClassDef,
        astroid.Import,
        astroid.ImportFrom,
    )
    for call in scope.nodes_of_class(astroid.Call, skip_klass=skip_nodes):
        inferred = utils.safe_infer(call.func)
        if (
            utils.is_builtin_object(inferred)
            and getattr(inferred, "name", None) == "locals"
        ):
            if stmt.lineno < call.lineno:
                return True
    return False 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:18,代碼來源:variables.py

示例11: visit_functiondef

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def visit_functiondef(self, node):
        if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno):
            return
        # If it is the first non import instruction of the module, record it.
        if self._first_non_import_node:
            return

        # Check if the node belongs to an `If` or a `Try` block. If they
        # contain imports, skip recording this node.
        if not isinstance(node.parent.scope(), astroid.Module):
            return

        root = node
        while not isinstance(root.parent, astroid.Module):
            root = root.parent

        if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
            if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
                return

        self._first_non_import_node = node 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:23,代碼來源:imports.py

示例12: _fix_dot_imports

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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 should be improved in issue astroid #46
    names = {}
    for name, stmts in six.iteritems(not_consumed):
        if any(isinstance(stmt, astroid.AssignName)
               and isinstance(stmt.assign_type(), astroid.AugAssign)
               for stmt in stmts):
            continue
        for stmt in stmts:
            if not isinstance(stmt, (astroid.ImportFrom, astroid.Import)):
                continue
            for imports in stmt.names:
                second_name = None
                if imports[0] == "*":
                    # In case of wildcard imports,
                    # pick the name from inside the imported module.
                    second_name = name
                else:
                    if imports[0].find(".") > -1 or name in imports:
                        # Most likely something like 'xml.etree',
                        # which will appear in the .locals as 'xml'.
                        # Only pick the name if it wasn't consumed.
                        second_name = imports[0]
                if second_name and second_name not in names:
                    names[second_name] = stmt
    return sorted(names.items(), key=lambda a: a[1].fromlineno) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:33,代碼來源:variables.py

示例13: _get_first_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
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
        if first.scope() is node.scope() and first.fromlineno > node.fromlineno:
            continue
        if isinstance(first, astroid.Import):
            if any(fullname == iname[0] for iname in first.names):
                found = True
                break
        elif isinstance(first, astroid.ImportFrom):
            if level == first.level:
                for imported_name, imported_alias in first.names:
                    if fullname == '%s.%s' % (first.modname, imported_name):
                        found = True
                        break
                    if name != '*' and name == imported_name and not (alias or imported_alias):
                        found = True
                        break
                if found:
                    break
    if found and not are_exclusive(first, node):
        return first
    return None 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:32,代碼來源:imports.py

示例14: compute_first_non_import_node

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def compute_first_non_import_node(self, node):
        if not self.linter.is_message_enabled('wrong-import-position', node.fromlineno):
            return
        # if the node does not contain an import instruction, and if it is the
        # first node of the module, keep a track of it (all the import positions
        # of the module will be compared to the position of this first
        # instruction)
        if self._first_non_import_node:
            return
        if not isinstance(node.parent, astroid.Module):
            return
        nested_allowed = [astroid.TryExcept, astroid.TryFinally]
        is_nested_allowed = [
            allowed for allowed in nested_allowed if isinstance(node, allowed)]
        if is_nested_allowed and \
                any(node.nodes_of_class((astroid.Import, astroid.ImportFrom))):
            return
        if isinstance(node, astroid.Assign):
            # Add compatibility for module level dunder names
            # https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names
            valid_targets = [
                isinstance(target, astroid.AssignName) and
                target.name.startswith('__') and target.name.endswith('__')
                for target in node.targets]
            if all(valid_targets):
                return
        self._first_non_import_node = node 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:29,代碼來源:imports.py

示例15: _set_module_environment

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import Import [as 別名]
def _set_module_environment(self, node: astroid.Module) -> None:
        """Method to set environment of a Module node."""
        node.type_environment = Environment()
        for name in node.globals:
            if not any(isinstance(elt, (astroid.ImportFrom, astroid.Import)) for elt in node.globals[name]):
                new_tvar = self.type_constraints.fresh_tvar(node.globals[name][0])
                if any(isinstance(elt, astroid.ClassDef) for elt in node.globals[name]):
                    self.type_constraints.unify(new_tvar, Type[ForwardRef(name)], node)
                node.type_environment.globals[name] = new_tvar
        self._populate_local_env(node) 
開發者ID:pyta-uoft,項目名稱:pyta,代碼行數:12,代碼來源:type_inference_visitor.py


注:本文中的astroid.Import方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。