本文整理汇总了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)
示例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
示例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
示例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
示例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
示例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))
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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))
示例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