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


Python astroid.ImportFrom方法代碼示例

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


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

示例1: test_importing_function_fails

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
def test_importing_function_fails(self):
        root = astroid.builder.parse("""
        from os.path import join
        from io import FileIO
        from os import environ
        from nonexistent_package import nonexistent_module
        def fnc():
            from other_nonexistent_package import nonexistent_module
        """)
        import_nodes = list(root.nodes_of_class(astroid.ImportFrom))
        tried_to_import = [
            'os.path.join',
            'io.FileIO',
            'os.environ',
            'nonexistent_package.nonexistent_module',
            'other_nonexistent_package.nonexistent_module',
        ]
        with self.assertAddsMessages(*[
                pylint.testutils.Message('import-modules-only', node=node, args={'child': child})
                for node, child in zip(import_nodes, tried_to_import)
        ]):
            self.walk(root) 
開發者ID:Shopify,項目名稱:shopify_python,代碼行數:24,代碼來源:test_google_styleguide.py

示例2: is_from_fallback_block

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例3: _find_frame_imports

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例4: _redefines_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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:AtomLinter,項目名稱:linter-pylama,代碼行數:21,代碼來源:base.py

示例5: visit_functiondef

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例6: _record_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
def _record_import(self, node, importedmodnode):
        """Record the package `node` imports from"""
        importedname = importedmodnode.name if importedmodnode else None
        if not importedname:
            if isinstance(node, astroid.ImportFrom):
                importedname = node.modname
            else:
                importedname = node.names[0][0].split('.')[0]
        if isinstance(node, astroid.ImportFrom) and (node.level or 0) >= 1:
            # We need the impotedname with first point to detect local package
            # Example of node:
            #  'from .my_package1 import MyClass1'
            #  the output should be '.my_package1' instead of 'my_package1'
            # Example of node:
            #  'from . import my_package2'
            #  the output should be '.my_package2' instead of '{pyfile}'
            importedname = '.' + importedname
        self._imports_stack.append((node, importedname)) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:20,代碼來源:imports.py

示例7: _get_assigns

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例8: visit_importfrom

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
def visit_importfrom(self, node):
        """visit an astroid.ImportFrom node

        resolve module dependencies
        """
        basename = node.modname
        context_file = node.root().file
        if context_file is not None:
            relative = modutils.is_relative(basename, context_file)
        else:
            relative = False
        for name in node.names:
            if name[0] == "*":
                continue
            # analyze dependencies
            fullname = "%s.%s" % (basename, name[0])
            if fullname.find(".") > -1:
                try:
                    # TODO: don't use get_module_part,
                    # missing package precedence
                    fullname = modutils.get_module_part(fullname, context_file)
                except ImportError:
                    continue
            if fullname != basename:
                self._imported_module(node, fullname, relative) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:27,代碼來源:inspector.py

示例9: is_defined_before

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例10: is_from_fallback_block

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例11: _has_locals_call_after_node

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例12: _get_import_name

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
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 isinstance(importnode, astroid.ImportFrom):
        if importnode.level:
            root = importnode.root()
            if isinstance(root, astroid.Module):
                modname = root.relative_to_absolute_name(
                    modname, level=importnode.level
                )
    return modname 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:18,代碼來源:imports.py

示例13: visit_functiondef

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [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

示例14: _record_import

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
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:
            importedname = node.names[0][0].split(".")[0]

        if isinstance(node, astroid.ImportFrom) and (node.level or 0) >= 1:
            # We need the importedname with first point to detect local package
            # Example of node:
            #  'from .my_package1 import MyClass1'
            #  the output should be '.my_package1' instead of 'my_package1'
            # Example of node:
            #  'from . import my_package2'
            #  the output should be '.my_package2' instead of '{pyfile}'
            importedname = "." + importedname

        self._imports_stack.append((node, importedname)) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:22,代碼來源:imports.py

示例15: using_future_annotations

# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import ImportFrom [as 別名]
def using_future_annotations(node: nc.NodeNG) -> nc.NodeNG:
    """Return whether postponed annotation evaluation is enabled (PEP 563)."""

    # Find the module.
    mnode = node
    while mnode.parent is not None:
        mnode = mnode.parent

    # Look for 'from __future__ import annotations' to decide
    # if we should assume all annotations are defer-eval'ed.
    # NOTE: this will become default at some point within a few years..
    annotations_set = mnode.locals.get('annotations')
    if (annotations_set and isinstance(annotations_set[0], astroid.ImportFrom)
            and annotations_set[0].modname == '__future__'):
        return True
    return False 
開發者ID:efroemling,項目名稱:ballistica,代碼行數:18,代碼來源:pylintplugins.py


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