當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。