• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ast.arguments函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __call__

    def __call__(self, selection):
        if not self.is_initialized:
            self._initialize()

        try:
            parse_result = self.expression.parseString(selection, parseAll=True)
        except ParseException as e:
            msg = str(e)
            lines = ["%s: %s" % (msg, selection),
                     " " * (12 + len("%s: " % msg) + (e.loc)) + "^^^"]
            raise ValueError('\n'.join(lines))


        # Change __ATOM__ in function bodies. It must bind to the arg
        # name specified below (i.e. 'atom')
        astnode = self.transformer.visit(deepcopy(parse_result[0].ast()))

        if PY2:
            args = [ast.Name(id='atom', ctx=ast.Param())]
            signature = ast.arguments(args=args, vararg=None, kwarg=None,
                                      defaults=[])
        else:
            args = [ast.arg(arg='atom', annotation=None)]
            signature = ast.arguments(args=args, vararg=None, kwarg=None,
                                      kwonlyargs=[], defaults=[],
                                      kw_defaults=[])

        func = ast.Expression(body=ast.Lambda(signature, astnode))
        source = codegen.to_source(astnode)

        expr = eval(
            compile(ast.fix_missing_locations(func), '<string>', mode='eval'),
            SELECTION_GLOBALS)
        return _ParsedSelection(expr, source, astnode)
开发者ID:ChayaSt,项目名称:mdtraj,代码行数:34,代码来源:selection.py


示例2: visit_GeneratorExp

    def visit_GeneratorExp(self, node):

        if node in self.optimizable_comprehension:

            self.generic_visit(node)

            iters = [self.make_Iterator(gen) for gen in node.generators]
            variables = [ast.Name(gen.target.id, ast.Param())
                         for gen in node.generators]

            # If dim = 1, product is useless
            if len(iters) == 1:
                iterAST = iters[0]
                varAST = ast.arguments([variables[0]], None, None, [])
            else:
                prodName = ast.Attribute(
                    value=ast.Name(id='itertools', ctx=ast.Load()),
                    attr='product', ctx=ast.Load())

                iterAST = ast.Call(prodName, iters, [], None, None)
                varAST = ast.arguments([ast.Tuple(variables, ast.Store())],
                                       None, None, [])

            imapName = ast.Attribute(
                value=ast.Name(id='itertools', ctx=ast.Load()),
                attr='imap', ctx=ast.Load())

            ldBodyimap = node.elt
            ldimap = ast.Lambda(varAST, ldBodyimap)

            return ast.Call(imapName, [ldimap, iterAST], [], None, None)

        else:
            return self.generic_visit(node)
开发者ID:yuancheng2013,项目名称:pythran,代码行数:34,代码来源:optimizations.py


示例3: visit_ListComp

    def visit_ListComp(self, node):

        if node in self.optimizable_comprehension:
            self.update = True
            self.generic_visit(node)

            iterList = []
            varList = []

            for gen in node.generators:
                iterList.append(self.make_Iterator(gen))
                varList.append(ast.Name(gen.target.id, ast.Param()))

            # If dim = 1, product is useless
            if len(iterList) == 1:
                iterAST = iterList[0]
                varAST = ast.arguments([varList[0]], None, None, [])
            else:
                prodName = ast.Attribute(value=ast.Name(id="itertools", ctx=ast.Load()), attr="product", ctx=ast.Load())

                iterAST = ast.Call(prodName, iterList, [], None, None)
                varAST = ast.arguments([ast.Tuple(varList, ast.Store())], None, None, [])

            mapName = ast.Attribute(value=ast.Name(id="__builtin__", ctx=ast.Load()), attr="map", ctx=ast.Load())

            ldBodymap = node.elt
            ldmap = ast.Lambda(varAST, ldBodymap)

            return ast.Call(mapName, [ldmap, iterAST], [], None, None)

        else:
            return self.generic_visit(node)
开发者ID:LuisBL,项目名称:pythran,代码行数:32,代码来源:list_comp_to_map.py


示例4: p_lambda

def p_lambda(p):
    """lambda : '@' '(' params ')' expr"""
    if p[3]:
        arg_names, defaults = tuple([filter(lambda x: x is not None, item) for item in zip(*p[3])])
        args = ast.arguments(list(arg_names), None, None, list(defaults))
    else:
        args = ast.arguments([], None, None, [])
    p[0] = ast.Lambda(args, p[5])
开发者ID:Tubebaum,项目名称:pltcatan,代码行数:8,代码来源:parser.py


示例5: p_func

def p_func(p):
    """func : FUNC ID '(' params ')' '{' opt_newline body '}'"""
    if p[4]:
        arg_names, defaults = tuple([filter(lambda x: x is not None, item) for item in zip(*p[4])])
        args = ast.arguments(list(arg_names), None, None, list(defaults))
    else:
        args = ast.arguments([], None, None, [])
    p[0] = ast.FunctionDef(p[2], args, p[8], [])
开发者ID:Tubebaum,项目名称:pltcatan,代码行数:8,代码来源:parser.py


示例6: p_top_func

def p_top_func(p):
    """topfunc : FUNC '(' params ')' '{' opt_newline body '}'"""
    if p[3]:
        args = ast.arguments([ast.Name('self', ast.Param())], None, None, [])
    else:
        args = ast.arguments([], None, None, [])
    p[7] = [RewriteInjected([param[0].id for param in p[3]]).visit(node) for node in p[7]]
    p[0] = [ast.FunctionDef("top", args, p[7], [])]
开发者ID:Tubebaum,项目名称:pltcatan,代码行数:8,代码来源:parser.py


示例7: test_arguments

    def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(1, 2, 3, 4)
        self.assertEqual(x.vararg, 2)
开发者ID:0xcc,项目名称:python-read,代码行数:9,代码来源:test_ast.py


示例8: make_lambda

def make_lambda(expression, args, env=None):
    # type: (ast.Expression, List[str], Dict[str, Any]) -> types.FunctionType
    """
    Create an lambda function from a expression AST.

    Parameters
    ----------
    expression : ast.Expression
        The body of the lambda.
    args : List[str]
        A list of positional argument names
    env : Optional[Dict[str, Any]]
        Extra environment to capture in the lambda's closure.

    Returns
    -------
    func : types.FunctionType
    """
    # lambda *{args}* : EXPRESSION
    lambda_ = ast.Lambda(
        args=ast.arguments(
            args=[ast.arg(arg=arg, annotation=None) for arg in args],
            varargs=None,
            varargannotation=None,
            kwonlyargs=[],
            kwarg=None,
            kwargannotation=None,
            defaults=[],
            kw_defaults=[]),
        body=expression.body,
    )
    lambda_ = ast.copy_location(lambda_, expression.body)
    # lambda **{env}** : lambda *{args}*: EXPRESSION
    outer = ast.Lambda(
        args=ast.arguments(
            args=[ast.arg(arg=name, annotation=None) for name in (env or {})],
            varargs=None,
            varargannotation=None,
            kwonlyargs=[],
            kwarg=None,
            kwargannotation=None,
            defaults=[],
            kw_defaults=[],
        ),
        body=lambda_,
    )
    exp = ast.Expression(body=outer, lineno=1, col_offset=0)
    ast.fix_missing_locations(exp)
    GLOBALS = __GLOBALS.copy()
    GLOBALS["__builtins__"] = {}
    # pylint: disable=eval-used
    fouter = eval(compile(exp, "<lambda>", "eval"), GLOBALS)
    assert isinstance(fouter, types.FunctionType)
    finner = fouter(**env)
    assert isinstance(finner, types.FunctionType)
    return finner
开发者ID:biolab,项目名称:orange3,代码行数:56,代码来源:owfeatureconstructor.py


示例9: p_function_def

def p_function_def(p):
    """function_def : type NAME new_scope LPAREN params_def_list RPAREN LBRACE func_statement_list RBRACE
                    | void NAME new_scope LPAREN params_def_list RPAREN LBRACE func_statement_list RBRACE
    """
    if len(p[8]) > 0:
        p[0] = ast.FunctionDef(name=p[2], args=ast.arguments(args=p[5], vararg=None, kwarg=None, defaults=[]), body=p[8], decorator_list=[], type=p[1], level=0, globals=global_names())
    else:
        p[0] = ast.FunctionDef(name=p[2], args=ast.arguments(args=p[5], vararg=None, kwarg=None, defaults=[]), body=[ast.Pass()], decorator_list=[], type=p[1], level=0, globals=global_names())
    pop_scope()
    symbol_stack[0].append(p[2])
开发者ID:blencho,项目名称:owl,代码行数:10,代码来源:parse.py


示例10: func_super

 def func_super(self, type_, inst):
     self.visit(
         ast_call(
             ast.FunctionDef(
                 '',
                 ast.arguments([ast_store('p'), ast_store('i')], None, None, []),
                 [
                     ast.FunctionDef(
                         'tmp',
                         ast.arguments([], None, None, []),
                         [
                             ast.Expr(
                                 ast_call(
                                     ast_load('this.__bind__'),
                                     ast_load('i')
                                 )
                             ),
                         ],
                         []
                     ),
                     ast.Assign(
                         [ast_load('tmp.prototype')],
                         ast_load('p')
                     ),
                     ast.Return(
                         ast_call(
                             ast_load('new'),
                             ast_load('tmp'),
                         )
                     )
                 ],
                 []
             ),
             ast.Attribute(
                 ast.Subscript(
                     ast_load('self.__mro__'),
                     ast.Index(
                         ast.BinOp(
                             ast_call(
                                 ast_load('self.__mro__.indexOf'),
                                 type_,
                             ),
                             ast.Sub(),
                             ast.Num(1)
                         )
                     ),
                     ast.Load()
                 ),
                 'prototype',
                 ast.Load()
             ),
             inst,
         )
     )
开发者ID:ztane,项目名称:jaspyx,代码行数:54,代码来源:func_super.py


示例11: test_arguments

    def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
                                      'kwonlyargs', 'kwarg', 'kwargannotation',
                                      'defaults', 'kw_defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(*range(1, 9))
        self.assertEqual(x.vararg, 2)
开发者ID:timm,项目名称:timmnix,代码行数:11,代码来源:test_ast.py


示例12: ast_lambda

def ast_lambda(name, body):
    if PYTHON_VERSION is 2:
        return ast.Lambda(args=ast.arguments(args=[name],
                          defaults=[]), body=body)
    elif PYTHON_VERSION is 3:
        return ast.Lambda(args=ast.arguments(args=[ast.arg(arg=name.id)],
                                             defaults=[],
                                             kwonlyargs=[],
                                             kw_defaults=[]),
                          body=body)
    else:
        invalid_python_version()
开发者ID:andorp,项目名称:monadic,代码行数:12,代码来源:decorator.py


示例13: map_args

 def map_args(self, arg_items, body):
     if len(arg_items) == 1:
         arg = ast.arguments(args=[arg_items[0]], vararg=None, kwarg=None, defaults=[])
         return arg, body
     arg = ast.Name(id=self.make_name("_a"), ctx=ast.Load())
     maps = self.get_slice(arg, arg_items)
     if isinstance(body, list):
         body = [NamesMapper(maps).visit(i) for i in body]
     else:
         body = NamesMapper(maps).visit(body)
     arg = ast.arguments(args=[arg], vararg=None, kwarg=None, defaults=[])
     return arg, body
开发者ID:Tefx,项目名称:Briareus,代码行数:12,代码来源:ast_mod.py


示例14: create_bind

 def create_bind(gs):
     l = len(gs)
     g = gs[0]
     iter_call = g.iter
     if l == 1:
         la = ast.Lambda(args=ast.arguments(args=[g.target], defaults=[]),
                         body=func_call(name('unit'), args=[node.elt])) # ast.Str(s="TODO")) # TODO
         return func_call(name('bind'), [iter_call, la])
     if l > 1:
         la = ast.Lambda(args=ast.arguments(args=[g.target], defaults=[]),
                         body=create_bind(gs[1:]))
         return func_call(name('bind'), [iter_call, la])
     raise Exception('Empty generators for list comprehension')
开发者ID:andorp,项目名称:py-contract,代码行数:13,代码来源:uncompile.py


示例15: decorator

    def decorator(wrapped):
        spec = inspect.getargspec(wrapped)
        name = wrapped.__name__

        assert spec.varargs is not None

        # Example was generated with print ast.dump(ast.parse("def f(a, b, *args, **kwds): return call_wrapped((a, b), args, kwds)"), include_attributes=True)
        # http://code.activestate.com/recipes/578353-code-to-source-and-back/ helped a lot
        # http://stackoverflow.com/questions/10303248#29927459
        if sys.hexversion < 0x03000000:
            wrapper_ast_args = ast.arguments(
                    args=[ast.Name(id=a, ctx=ast.Param(), lineno=1, col_offset=0) for a in spec.args],
                    vararg=spec.varargs,
                    kwarg=spec.keywords,
                    defaults=[]
                )
        else:
            wrapper_ast_args = ast.arguments(
                args=[ast.arg(arg=a, annotation=None, lineno=1, col_offset=0) for a in spec.args],
                vararg=None if spec.varargs is None else ast.arg(arg=spec.varargs, annotation=None, lineno=1, col_offset=0),
                kwonlyargs=[],
                kw_defaults=[],
                kwarg=None if spec.keywords is None else ast.arg(arg=spec.keywords, annotation=None, lineno=1, col_offset=0),
                defaults=[]
            )
        wrapper_ast = ast.Module(body=[ast.FunctionDef(
            name=name,
            args=wrapper_ast_args,
            body=[ast.Return(value=ast.Call(
                func=ast.Name(id="wrapped", ctx=ast.Load(), lineno=1, col_offset=0),
                args=[ast.Name(id=a, ctx=ast.Load(), lineno=1, col_offset=0) for a in spec.args],
                keywords=[],
                starargs=ast.Call(
                    func=ast.Name(id="flatten", ctx=ast.Load(), lineno=1, col_offset=0),
                    args=[ast.Name(id=spec.varargs, ctx=ast.Load(), lineno=1, col_offset=0)],
                    keywords=[], starargs=None, kwargs=None, lineno=1, col_offset=0
                ),
                kwargs=None if spec.keywords is None else ast.Name(id=spec.keywords, ctx=ast.Load(), lineno=1, col_offset=0),
                lineno=1, col_offset=0
            ), lineno=1, col_offset=0)],
            decorator_list=[],
            lineno=1,
            col_offset=0
        )])
        wrapper_code = [c for c in compile(wrapper_ast, "<ast_in_variadic_py>", "exec").co_consts if isinstance(c, types.CodeType)][0]
        wrapper = types.FunctionType(wrapper_code, {"wrapped": wrapped, "flatten": flatten}, argdefs=spec.defaults)

        functools.update_wrapper(wrapper, wrapped)
        if wrapper.__doc__ is not None:
            wrapper.__doc__ = "Note that this function is variadic. See :ref:`variadic-functions`.\n\n" + wrapper.__doc__
        return wrapper
开发者ID:jacquev6,项目名称:LowVoltage,代码行数:51,代码来源:variadic.py


示例16: compile_func

def compile_func(arg_names, statements, name='_the_func', debug=False):
    """Compile a list of statements as the body of a function and return
    the resulting Python function. If `debug`, then print out the
    bytecode of the compiled function.
    """
    if six.PY2:
        func_def = ast.FunctionDef(
            name=name.encode('utf-8'),
            args=ast.arguments(
                args=[ast.Name(n, ast.Param()) for n in arg_names],
                vararg=None,
                kwarg=None,
                defaults=[ex_literal(None) for _ in arg_names],
            ),
            body=statements,
            decorator_list=[],
        )
    else:
        func_def = ast.FunctionDef(
            name=name,
            args=ast.arguments(
                args=[ast.arg(arg=n, annotation=None) for n in arg_names],
                kwonlyargs=[],
                kw_defaults=[],
                defaults=[ex_literal(None) for _ in arg_names],
            ),
            body=statements,
            decorator_list=[],
        )

    # The ast.Module signature changed in 3.8 to accept a list of types to
    # ignore.
    if sys.version_info >= (3, 8):
        mod = ast.Module([func_def], [])
    else:
        mod = ast.Module([func_def])

    ast.fix_missing_locations(mod)

    prog = compile(mod, '<generated>', 'exec')

    # Debug: show bytecode.
    if debug:
        dis.dis(prog)
        for const in prog.co_consts:
            if isinstance(const, types.CodeType):
                dis.dis(const)

    the_locals = {}
    exec(prog, {}, the_locals)
    return the_locals[name]
开发者ID:beetbox,项目名称:beets,代码行数:51,代码来源:functemplate.py


示例17: compile_expr

 def compile_expr(self, target_type):
     if target_type is None:
         exprtype = None
     else:
         assert hasattr(target_type, 'paramtypes')
         assert hasattr(target_type, 'exprtype')
         exprtype = target_type.exprtype
     if _chill_util.python_version_major == 2:
         return _pyast.Lambda(
             _pyast.arguments([_pyast.Name(p, _pyast.Param()) for p in self.params], None, None, []),
             self.expr.compile_expr(exprtype))
     else:
         return _pyast.Lambda(
             _pyast.arguments([_pyast.arg(p, None) for p in self.params], None, None, [], None, None, [], []),
             self.expr.compile_expr(exprtype))
开发者ID:TharinduRusira,项目名称:chill-dev,代码行数:15,代码来源:_cpp_validate_env.py


示例18: getRTL

def getRTL():
    from ast import FunctionDef, For, Print, Name, Load, Store, arguments

    functions = []

    # imprimir(...)
    # Recibe cero o mas expresiones separadas por coma y las
    # imprme en pantalla separadas por un espacio
    #
    # Codigo Python
    # def imprimir(*args):
    #     for arg in args:
    #         print arg,
    #     print
    #
    functions.append(
        FunctionDef(
            name="imprimir",
            args=arguments(args=[], vararg="args", kwarg=None, defaults=[]),
            body=[
                For(
                    target=Name(id="arg", ctx=Store()),
                    iter=Name(id="args", ctx=Load()),
                    body=[Print(dest=None, values=[Name(id="arg", ctx=Load())], nl=False)],
                    orelse=[],
                ),
                Print(dest=None, values=[], nl=True),
            ],
            decorator_list=[],
        )
    )
    return functions
开发者ID:roskoff,项目名称:gSL,代码行数:32,代码来源:gSL.py


示例19: test_lambda

 def test_lambda(self):
     a = ast.arguments([], None, None, [], None, None, [], [])
     self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
               "must have Load context")
     def fac(args):
         return ast.Lambda(args, ast.Name("x", ast.Load()))
     self._check_arguments(fac, self.expr)
开发者ID:timm,项目名称:timmnix,代码行数:7,代码来源:test_ast.py


示例20: build_Assign_Destructuring

    def build_Assign_Destructuring(self, targets, value):
        scope = self.stack[-1].scope
        global_scope = scope.get_global_scope()

        assignments = []
        for target, i in zip(targets.elts, range(len(targets.elts))):
            if isinstance(target, _ast.Name):
                if scope.is_global(target.id):
                    global_scope.declare(target.id)
                else:
                    scope.declare(target.id)
                target = ast.Name(target.id, ast.Load())
            assignments.append(
                ast.Assign(
                    [target],
                    ast.Subscript(
                        ast_load('v'),
                        ast.Index(ast.Num(i)),
                        ast.Load()
                    )
                )
            )

        return ast_call(
            ast.FunctionDef(
                '',
                ast.arguments([ast_store('v')], None, None, []),
                assignments + [
                    ast.Return(ast_load('v'))
                ],
                []
            ),
            value
        )
开发者ID:ztane,项目名称:jaspyx,代码行数:34,代码来源:assign.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ast.comprehension函数代码示例发布时间:2022-05-24
下一篇:
Python ast.arg函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap