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


Python ast.Module方法代码示例

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


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

示例1: ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def ast(self) -> ast.Module:  # type: ignore
        """Abstract Syntax Tree (AST) representation of the source_file.

        This is cached locally and updated if the source_file is changed.

        Returns:
            Parsed AST for the source file.

        Raises:
            TypeError: if ``source_file`` is not set.
        """
        if self._ast is None:
            if not self.source_file:
                raise TypeError("Source_file property is set to NoneType.")

            with open(self.source_file, "rb") as src_stream:
                self._ast = ast.parse(src_stream.read())
        return self._ast 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:20,代码来源:api.py

示例2: generic_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def generic_visit(self, node):
        # Fallback when we don't have a special implementation.
        if _is_ast_expr(node):
            mod = ast.Expression(node)
            co = self._compile(mod)
            try:
                result = self.frame.eval(co)
            except Exception:
                raise Failure()
            explanation = self.frame.repr(result)
            return explanation, result
        elif _is_ast_stmt(node):
            mod = ast.Module([node])
            co = self._compile(mod, "exec")
            try:
                self.frame.exec_(co)
            except Exception:
                raise Failure()
            return None, None
        else:
            raise AssertionError("can't handle %s" %(node,)) 
开发者ID:pytest-dev,项目名称:py,代码行数:23,代码来源:_assertionnew.py

示例3: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0):
        'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call'
        if isinstance(patt_ast, ast.Module):
            self.patt_ast = patt_ast.body[0].value
        elif isinstance(patt_ast, ast.Expression):
            self.patt_ast = patt_ast.body
        else:
            self.patt_ast = patt_ast
        if isinstance(rep_ast, ast.Module):
            self.rep_ast = deepcopy(rep_ast.body[0].value)
        elif isinstance(rep_ast, ast.Expression):
            self.rep_ast = deepcopy(rep_ast.body)
        else:
            self.rep_ast = deepcopy(rep_ast)

        if not nbits:
            getsize = asttools.GetSize()
            getsize.visit(target_ast)
            if getsize.result:
                self.nbits = getsize.result
            # default bitsize is 8
            else:
                self.nbits = 8
        else:
            self.nbits = nbits 
开发者ID:quarkslab,项目名称:sspam,代码行数:27,代码来源:pattern_matcher.py

示例4: test_dump

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:test_ast.py

示例5: test_topython_generates_code_for_alt

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def test_topython_generates_code_for_alt(self):
        alt = parsing.Alt(
            ParseTreeStub('a', False), ParseTreeStub('b', False))
        res = codegen.to_source(ast.Module(passes.rule_topython(alt)))
        self.assertEqual(res, ("try:\n"
                               "    try:\n"
                               "        if (not a):\n"
                               "            raise AltFalse()\n"
                               "        raise AltTrue()\n"
                               "    except AltFalse:\n"
                               "        pass\n"
                               "    try:\n"
                               "        if (not b):\n"
                               "            raise AltFalse()\n"
                               "        raise AltTrue()\n"
                               "    except AltFalse:\n"
                               "        pass\n"
                               "    return False\n"
                               "except AltTrue:\n"
                               "    pass")) 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:22,代码来源:test_topython.py

示例6: new_functionCFG

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def new_functionCFG(self, node, asynchr=False):
        """
        Create a new sub-CFG for a function definition and add it to the
        function CFGs of the CFG being built.

        Args:
            node: The AST node containing the function definition.
            async: Boolean indicating whether the function for which the CFG is
                   being built is asynchronous or not.
        """
        self.current_id += 1
        # A new sub-CFG is created for the body of the function definition and
        # added to the function CFGs of the current CFG.
        func_body = ast.Module(body=node.body)
        func_builder = CFGBuilder()
        self.cfg.functioncfgs[node.name] = func_builder.build(node.name,
                                                              func_body,
                                                              asynchr,
                                                              self.current_id)
        self.current_id = func_builder.current_id + 1 
开发者ID:coetaur0,项目名称:staticfg,代码行数:22,代码来源:builder.py

示例7: transform_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def transform_ast(self, node):
        """Apply the AST transformations from self.ast_transformers
        
        Parameters
        ----------
        node : ast.Node
          The root node to be transformed. Typically called with the ast.Module
          produced by parsing user input.
        
        Returns
        -------
        An ast.Node corresponding to the node it was called with. Note that it
        may also modify the passed object, so don't rely on references to the
        original AST.
        """
        for transformer in self.ast_transformers:
            try:
                node = transformer.visit(node)
            except Exception:
                warn("AST transformer %r threw an error. It will be unregistered." % transformer)
                self.ast_transformers.remove(transformer)
        
        if self.ast_transformers:
            ast.fix_missing_locations(node)
        return node 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:27,代码来源:interactiveshell.py

示例8: find_func

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def find_func(module, namespace):
    """Filter away everything except the function

    Addionally rename the function for better readability.

    Args:
        module (ast.Module): the entire parsed code
        namespace (str): identifier for the function of interest

    `namspace` will be of the form <module_name>.<function_name>

    Returns:
        module (ast.Module): the original module but with everything filtered
        away except the function and the function with a more readable name

    """
    module_name, func_name = namespace.split('.')
    funcs = [stmt for stmt in module.body if isinstance(stmt, ast.FunctionDef)]
    func, = [func for func in funcs if func.name == func_name]
    func.name = f'{module_name}.{func_name}'
    module.body = [func]
    return module 
开发者ID:ebanner,项目名称:pynt,代码行数:24,代码来源:syntax.py

示例9: find_method

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def find_method(module, namespace):
    """Filter away everything except the method

    Promote the method up to the global namespace so that it is
    indistinguishable from a regular function.

    Arguments:
        module (ast.Module): the entire parsed source code
        namespace (str): identifier for the method of interest

    Returns:
        module (ast.Module): the original module but with everything filtered
        away except the method name but with the name `namespace` and promoted
        to the global (i.e. top) level

    """
    module_name, class_name, method_name = namespace.split('.')
    classdefs = [stmt for stmt in module.body if isinstance(stmt, ast.ClassDef)]
    classdef, = [classdef for classdef in classdefs if classdef.name == class_name]
    methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)]
    for method in methods:
        if method.name == method_name:
            method.name = f'{module_name}.{class_name}.{method_name}'
            module.body = [method]
            return module 
开发者ID:ebanner,项目名称:pynt,代码行数:27,代码来源:syntax.py

示例10: CheckedEval

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  syntax_tree = ast.parse(file_contents)
  assert isinstance(syntax_tree, ast.Module)
  c1 = syntax_tree.body
  assert len(c1) == 1
  c2 = c1[0]
  assert isinstance(c2, ast.Expr)
  return CheckNode(c2.value, []) 
开发者ID:refack,项目名称:GYP3,代码行数:18,代码来源:input.py

示例11: test_progn_uses_custom_eval_fn

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def test_progn_uses_custom_eval_fn(self):
        """
        Assert that the progn function uses custom eval functions properly.
        """
        eval_fn = mock.MagicMock()

        try:
            progn('2 + 2', eval_fn=eval_fn)
        except QdbPrognEndsInStatement:
            # This is the error that we are getting because our eval function
            # is not storing any results.
            pass

        calls = eval_fn.call_args_list

        self.assertEqual(len(calls), 1)
        call_args = calls[0][0]

        # This is constructed inside the function, but should be a module.
        self.assertIsInstance(call_args[0], ast.Module)
        self.assertEqual(call_args[1], sys._getframe())
        self.assertEqual(call_args[2], 'exec') 
开发者ID:quantopian,项目名称:qdb,代码行数:24,代码来源:test_misc.py

示例12: from_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def from_ast(cls, tree: ast.Module) -> List['Func']:
        funcs = []
        for expr in tree.body:
            if not isinstance(expr, ast.FunctionDef):
                continue
            contracts = []
            for category, args in get_contracts(expr.decorator_list):
                contract = Contract(
                    args=args,
                    category=Category(category),
                    func_args=expr.args,
                )
                contracts.append(contract)
            funcs.append(cls(
                name=expr.name,
                args=expr.args,
                body=expr.body,
                contracts=contracts,
                line=expr.lineno,
                col=expr.col_offset,
            ))
        return funcs 
开发者ID:life4,项目名称:deal,代码行数:24,代码来源:_func.py

示例13: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def __init__(
        self,
        source_file: Optional[Union[str, Path]] = None,
        coverage_file: Optional[Union[str, Path]] = Path(".coverage"),
        filter_codes: Optional[Iterable[str]] = None,
    ) -> None:
        """Initialize the Genome.

        There are internal properties prefixed with an underscore used for the lazy evaluation
        of the AST and mutation targets.

        Args:
            source_file: an optional source file path
            coverage_file: coverage file for filtering covered lines,
                default value is set to ".coverage".
            filter_codes: 2-letter category codes to filter returned targets
        """
        # Properties with an underscore prefix are used for local caching and are not designed
        # to be modified directly.
        # Related to source files, AST, targets
        self._source_file = None
        self._ast: Optional[ast.Module] = None
        self._targets: Optional[Set[LocIndex]] = None

        # Related to coverage filtering
        self._coverage_file = None
        self._covered_targets: Optional[Set[LocIndex]] = None

        # Related to category code filtering, not cached but uses a setter for valid value checks
        self._filter_codes: Set[str] = set()

        # Initialize set values using properties
        # These may be set later and clear the cached values in the setters
        self.source_file = Path(source_file) if source_file else None
        self.coverage_file = Path(coverage_file) if coverage_file else None
        self.filter_codes: Set[str] = set(filter_codes) if filter_codes else set()

    ################################################################################################
    # CATEGORY FILTER CODES PROPERTIES
    ################################################################################################ 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:42,代码来源:api.py

示例14: _find_value_of

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def _find_value_of(mod_ast, target):
  """Looks for an assignment to `target`, returning the assignment value AST
  node and the line number of the assignment.

  Example:

     some_var = 100
     other = 20 + 10

     _find_value_of(<code>, 'some_var')  ->  ast.Num(100)

  Args:
    * mod_ast (ast.Module) - The parsed Python module code.
    * target (str) - The variable name to look for an assignment to.

  Returns the Python AST object which is the right-hand-side of an assignment to
  `target`.
  """
  assert isinstance(mod_ast, ast.Module), type(mod_ast)
  for node in mod_ast.body:
    if isinstance(node, ast.Assign):
      if (len(node.targets) == 1 and
          isinstance(node.targets[0], ast.Name) and
          node.targets[0].id == target):
        return node.value, node.lineno
  return None, None 
开发者ID:luci,项目名称:recipes-py,代码行数:28,代码来源:cmd.py

示例15: parse_deps

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Module [as 别名]
def parse_deps(repo_name, mod_ast, relpath):
  """Finds and parses the `DEPS` variable out of `mod_ast`.

  Args:
    * repo_name (str) - The implicit repo_name for DEPS entries which do not
      specify one.
    * mod_ast (ast.Module) - The Python module AST to parse from.
    * relpath (str) - The posix-style relative path which should be associated
      with the code in class_ast.

  Returns Doc.Deps proto messsage.
  """
  assert isinstance(mod_ast, ast.Module), type(mod_ast)
  ret = None

  DEPS, lineno = _find_value_of(mod_ast, 'DEPS')
  if DEPS:
    ret = doc.Doc.Deps(
      relpath=relpath,
      lineno=lineno,
    )
    spec = parse_deps_spec(repo_name, ast.literal_eval(_unparse(DEPS)))
    for dep_repo_name, mod_name in sorted(spec.itervalues()):
      ret.module_links.add(repo_name=dep_repo_name, name=mod_name)

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


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