当前位置: 首页>>代码示例>>Python>>正文


Python ast.ImportFrom方法代码示例

本文整理汇总了Python中ast.ImportFrom方法的典型用法代码示例。如果您正苦于以下问题:Python ast.ImportFrom方法的具体用法?Python ast.ImportFrom怎么用?Python ast.ImportFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.ImportFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_top_imported_names

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def get_top_imported_names(file: str) -> Set[str]:
    """Collect names imported in given file.

    We only collect top-level names, i.e. `from foo.bar import baz`
    will only add `foo` to the list.
    """
    if not file.endswith(".pyi"):
        return set()
    with open(os.path.join(file), "rb") as f:
        content = f.read()
    parsed = ast.parse(content)
    top_imported = set()
    for node in ast.walk(parsed):
        if isinstance(node, ast.Import):
            for name in node.names:
                top_imported.add(name.name.split('.')[0])
        elif isinstance(node, ast.ImportFrom):
            if node.level > 0:
                # Relative imports always refer to the current package.
                continue
            assert node.module
            top_imported.add(node.module.split('.')[0])
    return top_imported 
开发者ID:python,项目名称:typeshed,代码行数:25,代码来源:migrate_script.py

示例2: _find_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def _find_imports(self, node):
        """Recurses through AST collecting the targets of all import
        statements."""
        if isinstance(node, ast.Import):
            return {self._extract_root_module(alias.name) for alias in node.names}
        elif isinstance(node, ast.ImportFrom):
            # We ignore all imports with levels other than 0. That's because if
            # if level > 0, we know that it's a relative import, and we only
            # care about root modules.
            if node.level == 0:
                return {self._extract_root_module(node.module)}
            else:
                return set()
        elif hasattr(node, 'body') and hasattr(node.body, '__iter__'):
            # Not all bodies are lists (for ex. exec)
            imps = set()
            for child_node in node.body:
                imps.update(self._find_imports(child_node))
            return imps
        else:
            return set() 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:23,代码来源:module_dependency.py

示例3: _parse_mock_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def _parse_mock_imports(mod_ast, expanded_imports):
  """Parses a module AST node for import statements and resolves them against
  expanded_imports (such as you might get from _expand_mock_imports).

  If an import is not recognized, it is omitted from the returned dictionary.

  Returns a dictionary suitable for eval'ing a statement in mod_ast, with
  symbols from mod_ast's imports resolved to real objects, as per
  expanded_imports.
  """
  ret = {}

  for node in mod_ast.body:
    if isinstance(node, ast.Import):
      for alias in node.names:
        if alias.name in expanded_imports:
          ret[alias.asname or alias.name] = expanded_imports[alias.name]
    elif isinstance(node, ast.ImportFrom):
      if node.level == 0:
        for alias in node.names:
          fullname ='%s.%s' % (node.module, alias.name)
          if fullname in expanded_imports:
            ret[alias.asname or alias.name] = expanded_imports[fullname]

  return ret 
开发者ID:luci,项目名称:recipes-py,代码行数:27,代码来源:cmd.py

示例4: handleNode

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def handleNode(self, node, parent):
        if node is None:
            return
        if self.offset and getattr(node, 'lineno', None) is not None:
            node.lineno += self.offset[0]
            node.col_offset += self.offset[1]
        if self.traceTree:
            print('  ' * self.nodeDepth + node.__class__.__name__)
        if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
                                        self.isDocstring(node)):
            self.futuresAllowed = False
        self.nodeDepth += 1
        node.depth = self.nodeDepth
        node.parent = parent
        try:
            handler = self.getNodeHandler(node.__class__)
            handler(node)
        finally:
            self.nodeDepth -= 1
        if self.traceTree:
            print('  ' * self.nodeDepth + 'end ' + node.__class__.__name__) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:23,代码来源:checker.py

示例5: _get_modules

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def _get_modules(self, content) -> Set[str]:
        imports = set()
        tree = ast.parse(content)
        for node in ast.walk(tree):
            if isinstance(node, ast.Import):
                for subnode in node.names:
                    imports.add(subnode.name)
            elif isinstance(node, ast.ImportFrom) and node.level == 0:
                imports.add(node.module)
        modules = set()
        for module in imports:
            if not module:
                continue
            module = module.split('.', maxsplit=1)[0]
            if module in self.stdlib:
                continue
            module = self.aliases.get(module, module)
            modules.add(module)
        return modules 
开发者ID:dephell,项目名称:dephell,代码行数:21,代码来源:imports.py

示例6: visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def visit(self, node) -> Any:
        if isinstance(node, ast.Name):
            if isinstance(node.ctx, ast.Load):
                self.loaded.add(node.id)
            elif isinstance(node.ctx, ast.Store):
                self.stored.add(node.id)
        elif isinstance(node, ast.Return):
            self.has_return = True
        # We must keep track of importer name in order to avoid considering as variable
        # names:
        elif isinstance(node, ast.Import):
            self.imported.update([ n.name for n in node.names])
        elif isinstance(node, ast.ImportFrom):
            self.imported.update([ n.name for n in node.names])

        self.generic_visit(node) 
开发者ID:Orange-OpenSource,项目名称:pyDcop,代码行数:18,代码来源:expressionfunction.py

示例7: add_custom_type_symbol

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def add_custom_type_symbol(self,
                               custom_type: ir2.CustomType,
                               definition_ast_node: Union[ast.ClassDef, ast.ImportFrom, None],
                               source_module: Optional[str] = None):
        self.add_symbol(name=custom_type.name,
                        expr_type=ir2.FunctionType(argtypes=tuple(arg.expr_type
                                                                  for arg in custom_type.arg_types),
                                                   argnames=tuple(arg.name
                                                                  for arg in custom_type.arg_types),
                                                   returns=custom_type),
                        definition_ast_node=definition_ast_node,
                        is_only_partially_defined=False,
                        is_function_that_may_throw=False)
        self.custom_types_symbol_table.add_symbol(name=custom_type.name,
                                                  expr_type=custom_type,
                                                  definition_ast_node=definition_ast_node,
                                                  is_only_partially_defined=False,
                                                  is_function_that_may_throw=False,
                                                  source_module=source_module) 
开发者ID:google,项目名称:tmppy,代码行数:21,代码来源:_ast_to_ir2.py

示例8: add_symbol_for_external_elem

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def add_symbol_for_external_elem(self,
                                     elem: Union[ir2.FunctionDefn, ir2.CustomType],
                                     import_from_ast_node: ast.ImportFrom,
                                     source_module: str):
        if isinstance(elem, ir2.FunctionDefn):
            self.add_symbol(name=elem.name,
                            expr_type=ir2.FunctionType(argtypes=tuple(arg.expr_type for arg in elem.args),
                                                       argnames=tuple(arg.name for arg in elem.args),
                                                       returns=elem.return_type),
                            definition_ast_node=import_from_ast_node,
                            is_only_partially_defined=False,
                            is_function_that_may_throw=True,
                            source_module=source_module)
        elif isinstance(elem, ir2.CustomType):
            self.add_custom_type_symbol(custom_type=elem,
                                        definition_ast_node=import_from_ast_node,
                                        source_module=source_module)
        else:
            raise NotImplementedError('Unexpected elem type: %s' % elem.__class__.__name__) 
开发者ID:google,项目名称:tmppy,代码行数:21,代码来源:_ast_to_ir2.py

示例9: find_globals

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def find_globals(g, tree):
    """Uses AST to find globals in an ast tree"""
    for child in tree:
        if hasattr(child, 'body') and isinstance(child.body, list):
            find_globals(g, child.body)
        elif isinstance(child, (ast.FunctionDef, ast.ClassDef)):
            g.add(child.name)
            continue
        elif isinstance(child, ast.Assign):
            try:
                g.add(child.targets[0].id)
            except (IndexError, AttributeError):
                pass
        elif isinstance(child, ast.Import):
            g.add(child.names[0].name)
        elif isinstance(child, ast.ImportFrom):
            for name in child.names:
                g_name = name.asname or name.name
                if g_name == '*':
                    continue
                g.add(g_name) 
开发者ID:sivel,项目名称:ansible-testing,代码行数:23,代码来源:utils.py

示例10: get_local_module_reqs

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def get_local_module_reqs(mod):
    tree = ast.parse(inspect.getsource(mod))
    imports = []
    for statement in tree.body:
        if isinstance(statement, ast.Import):
            imports += [(n.name, None) for n in statement.names]
        elif isinstance(statement, ast.ImportFrom):
            if statement.level == 0:
                imp = (statement.module, None)
            else:
                imp = ('.' + statement.module, mod.__package__)
            imports.append(imp)

    result = [import_module(i, p) for i, p in imports]
    if mod.__file__.endswith('__init__.py'):
        # add loaded subpackages
        prefix = mod.__name__ + '.'
        result += [mod for name, mod in sys.modules.items() if name.startswith(prefix)]
    return result 
开发者ID:zyfra,项目名称:ebonite,代码行数:21,代码来源:module.py

示例11: handleNode

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def handleNode(self, node, parent):
        if node is None:
            return
        if self.offset and getattr(node, 'lineno', None) is not None:
            node.lineno += self.offset[0]
            node.col_offset += self.offset[1]
        if self.traceTree:
            print('  ' * self.nodeDepth + node.__class__.__name__)
        if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
                                        self.isDocstring(node)):
            self.futuresAllowed = False
        self.nodeDepth += 1
        node._pyflakes_depth = self.nodeDepth
        node._pyflakes_parent = parent
        try:
            handler = self.getNodeHandler(node.__class__)
            handler(node)
        finally:
            self.nodeDepth -= 1
        if self.traceTree:
            print('  ' * self.nodeDepth + 'end ' + node.__class__.__name__) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:23,代码来源:checker.py

示例12: should_trace

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def should_trace(source):
    trace_stmt = None
    deep = False
    for stmt in ast.parse(source).body:
        if isinstance(stmt, ast.Import):
            for alias in stmt.names:
                if alias.name.startswith('birdseye.trace_module'):
                    trace_stmt = stmt
                    if alias.name.endswith('deep'):
                        deep = True

        if isinstance(stmt, ast.ImportFrom) and stmt.module == 'birdseye':
            for alias in stmt.names:
                if alias.name.startswith('trace_module'):
                    trace_stmt = stmt
                    if alias.name.endswith('deep'):
                        deep = True
    return deep, trace_stmt 
开发者ID:alexmojaki,项目名称:executing,代码行数:20,代码来源:import_hook.py

示例13: find_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def find_imports(code):
    """
    Finds the imports in a string of code and returns a list of their package
    names.
    """
    # handle mis-indented input from multi-line strings
    code = dedent(code)

    mod = ast.parse(code)
    imports = set()
    for node in ast.walk(mod):
        if isinstance(node, ast.Import):
            for name in node.names:
                name = name.name
                imports.add(name.split(".")[0])
        elif isinstance(node, ast.ImportFrom):
            name = node.module
            imports.add(name.split(".")[0])
    return list(imports) 
开发者ID:iodide-project,项目名称:pyodide,代码行数:21,代码来源:pyodide.py

示例14: visit_ImportFrom

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
        if node.col_offset == 0:
            if not node.level:
                assert node.module is not None  # true for node.level == 0
                self._maybe_append_name(node.module) 
开发者ID:asottile,项目名称:seed-isort-config,代码行数:7,代码来源:seed_isort_config.py

示例15: get_all_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ImportFrom [as 别名]
def get_all_imports(root):
    return get_nodes_of_type(root, (ast.ImportFrom, ast.Import)) 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:4,代码来源:ast_helpers.py


注:本文中的ast.ImportFrom方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。