当前位置: 首页>>代码示例>>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;未经允许,请勿转载。