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


Python ast.Load方法代码示例

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


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

示例1: visit_Expr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Expr(self, node):
        newnode = ast.copy_location(ast.Expr(
                value = ast.Call(
                    func = ast.Attribute(
                        value = ast.Name(id='__swirlypy_recorder__',
                                    ctx=ast.Load()),
                                    attr="record",
                                    ctx=ast.Load()),
                                    args=[node.value],
                                    keywords=[],
                                    starargs=None,
                                    kwargs=None
                        )
                    ),
                node)
        ast.fix_missing_locations(newnode)
        return newnode 
开发者ID:alexander-bauer,项目名称:swirlypy,代码行数:19,代码来源:Recording.py

示例2: NAME

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:21,代码来源:checker.py

示例3: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def __init__(
            self,
            keys: t.List[ast.expr],
            values: t.List[ast.expr],
            ctx: t.Union[ast.Store, ast.Load],
            lineno=None,
            col_offset=None,
    ):
        super().__init__()
        self.keys = keys
        self.values = values
        self.ctx = ctx
        if lineno:
            self.lineno = lineno
        if col_offset:
            self.col_offset = col_offset 
开发者ID:Xython,项目名称:YAPyPy,代码行数:18,代码来源:extended_ast.py

示例4: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx.__class__
        if ctx == ast.Load:
            # resolve the value
            resolved = self.visit(value)

            # try to get the value to see if we are another expression
            try:
                resolved = resolved.value
            except (AttributeError):
                pass

            try:
                return self.term_type(getattr(resolved, attr), self.env)
            except AttributeError:

                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}"
                         .format(name=ctx.__name__)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:pytables.py

示例5: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx
        if isinstance(ctx, ast.Load):
            # resolve the value
            resolved = self.visit(value).value
            try:
                v = getattr(resolved, attr)
                name = self.env.add_tmp(v)
                return self.term_type(name, self.env)
            except AttributeError:
                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}"
                         .format(name=ctx.__name__)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:expr.py

示例6: visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [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: test_noflattening

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def test_noflattening(self):
        'Tests where nothing should be flattened'
        corresp = [(["a + b", "b + a"],
                   ast.BinOp(ast.Name('a', ast.Load()),
                             ast.Add(),
                             ast.Name('b', ast.Load()))),
                   (["c*d", "d*c"],
                    ast.BinOp(ast.Name('c', ast.Load()),
                              ast.Mult(),
                              ast.Name('d', ast.Load()))),
                   (["a + c*d", "d*c + a"],
                    ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
                              ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(),
                                        ast.Name('d', ast.Load()))))]
        for refstring, result in corresp:
            self.generic_flattening(refstring, result) 
开发者ID:quarkslab,项目名称:sspam,代码行数:18,代码来源:test_flattening.py

示例8: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_BinOp(self, node):
        'Replace bitwise operation with function call'
        self.generic_visit(node)
        if isinstance(node.op, ast.BitAnd):
            return ast.Call(ast.Name('mand', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.BitOr):
            return ast.Call(ast.Name('mor', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.BitXor):
            return ast.Call(ast.Name('mxor', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.LShift):
            return ast.Call(ast.Name('mlshift', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.RShift):
            return ast.Call(ast.Name('mrshift', ast.Load()),
                            [node.left, node.right], [], None, None)
        return node 
开发者ID:quarkslab,项目名称:sspam,代码行数:21,代码来源:asttools.py

示例9: pop_format_context

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def pop_format_context(self, expl_expr):
        """Format the %-formatted string with current format context.

        The expl_expr should be an ast.Str instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:22,代码来源:rewrite.py

示例10: test_dump

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [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

示例11: test_attributes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def test_attributes(self):
        # assert True, "bad"
        assert0 = ast.Assert()
        self.assertFalse(hasattr(assert0, 'lineno'))
        self.assertFalse(hasattr(assert0, 'col_offset'))
        assert1 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'))
        self.assertFalse(hasattr(assert1, 'lineno'))
        self.assertFalse(hasattr(assert1, 'col_offset'))
        try:
            tmp=assert1.lineno
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        try:
            tmp=assert1.col_offset
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        assert2 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'),2,3)
        self.assertEqual(assert2.lineno,2)
        self.assertEqual(assert2.col_offset,3) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:test_ast.py

示例12: __exit_scope

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def __exit_scope(self) -> ast.stmt:
        """Create the appropriate scope exiting statement.

        The documentation only shows one level and always uses
        'return False' in examples.

        'raise AltFalse()' within a try.
        'break' within a loop.
        'return False' otherwise.
        """
        if self.in_optional:
            return ast.Pass()
        if self.in_try:
            return ast.Raise(
                ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
                None)
        if self.in_loop:
            return ast.Break()
        return ast.Return(ast.Name('False', ast.Load()))

    #TODO(bps): find a better name to describe what this does 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:23,代码来源:topython.py

示例13: visit_Hook

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Hook(self, node: parsing.Hook) -> ast.expr:
        """Generates python code calling a hook.

        self.evalHook('hookname', self.ruleNodes[-1])
        """
        return ast.Call(
            ast.Attribute(
                ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
            [
                ast.Str(node.name),
                ast.Subscript(
                    ast.Attribute(
                        ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
                    ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
                    ast.Load())],
            [],
            None,
            None) 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:20,代码来源:topython.py

示例14: visit_Rep0N

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
        """Generates python code for a clause repeated 0 or more times.

        #If all clauses can be inlined
        while clause:
            pass

        while True:
            <code for the clause>
        """
        cl_ast = self.visit(node.pt)
        if isinstance(cl_ast, ast.expr):
            return [ast.While(cl_ast, [ast.Pass()], [])]
        self.in_loop += 1
        clause = self._clause(self.visit(node.pt))
        self.in_loop -= 1
        return [ast.While(ast.Name('True', ast.Load()), clause, [])] 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:19,代码来源:topython.py

示例15: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx.__class__
        if ctx == ast.Load:
            # resolve the value
            resolved = self.visit(value)

            # try to get the value to see if we are another expression
            try:
                resolved = resolved.value
            except (AttributeError):
                pass

            try:
                return self.term_type(getattr(resolved, attr), self.env)
            except AttributeError:

                # something like datetime.datetime where scope is overriden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {0}".format(ctx.__name__)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:26,代码来源:pytables.py


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