本文整理汇总了Python中ast.arguments函数的典型用法代码示例。如果您正苦于以下问题:Python arguments函数的具体用法?Python arguments怎么用?Python arguments使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了arguments函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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)
示例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])
示例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], [])
示例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], [])]
示例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)
示例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
示例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])
示例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,
)
)
示例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)
示例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()
示例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
示例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')
示例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