本文整理汇总了Python中ast.keyword函数的典型用法代码示例。如果您正苦于以下问题:Python keyword函数的具体用法?Python keyword怎么用?Python keyword使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了keyword函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_Call
def test_Call(self):
name = ast.Name('spam', ast.Load())
args = ([ast.Num(42)], '42'), ([], None)
keywords = ([ast.keyword('X', ast.Num(42))], 'X=42'), ([], None)
starargs = (ast.Name('args', ast.Load()), '*args'), (None, None)
kwargs = (ast.Name('kwargs', ast.Load()), '**kwargs'), (None, None)
for arg in args:
for keyword in keywords:
for stararg in starargs:
for kwarg in kwargs:
node = ast.Call(name, arg[0], keyword[0], stararg[0],
kwarg[0])
expect = 'spam({})'.format(','.join(x for x in
(arg[1], keyword[1], stararg[1], kwarg[1])
if x))
self.verify(node, expect)
self.verify(ast.Call(name, [ast.Num(2), ast.Num(3)], [], None, None),
'spam(2,3)')
self.verify(ast.Call(name, [],
[ast.keyword('X', ast.Num(0)),
ast.keyword('Y', ast.Num(1))],
None, None),
'spam(X=0,Y=1)')
# A single genexp doesn't need parentheses.
genexp = self.seq_comp_test(ast.GeneratorExp, '()')
self.verify(ast.Call(name, [genexp], [], None, None),
'spam(w for x in y if 2 for a in b)')
self.verify(ast.Call(name, [genexp, genexp], [], None, None),
'spam((w for x in y if 2 for a in b),'
'(w for x in y if 2 for a in b))')
示例2: _compile_directive_call_assets
def _compile_directive_call_assets(self, el, options):
""" This special 't-call' tag can be used in order to aggregate/minify javascript and css assets"""
if len(el):
raise SyntaxError("t-call-assets cannot contain children nodes")
# self._get_asset(xmlid, options, css=css, js=js, debug=values.get('debug'), async=async, values=values)
return [
self._append(ast.Call(
func=ast.Attribute(
value=ast.Name(id='self', ctx=ast.Load()),
attr='_get_asset',
ctx=ast.Load()
),
args=[
ast.Str(el.get('t-call-assets')),
ast.Name(id='options', ctx=ast.Load()),
],
keywords=[
ast.keyword('css', self._get_attr_bool(el.get('t-css', True))),
ast.keyword('js', self._get_attr_bool(el.get('t-js', True))),
ast.keyword('debug', ast.Call(
func=ast.Attribute(
value=ast.Name(id='values', ctx=ast.Load()),
attr='get',
ctx=ast.Load()
),
args=[ast.Str('debug')],
keywords=[], starargs=None, kwargs=None
)),
ast.keyword('async', self._get_attr_bool(el.get('async', False))),
ast.keyword('values', ast.Name(id='values', ctx=ast.Load())),
],
starargs=None, kwargs=None
))
]
示例3: test_keywords_wildcard
def test_keywords_wildcard(self):
apf = ASTPatternFinder(prepare_pattern("f(e=4, ??=??)"))
it = apf.scan_ast(self.ast)
assert_ast_like(next(it), ast.Call(keywords=[ast.keyword(arg='d'),
ast.keyword(arg='e'),])
)
self.assert_no_more(it)
示例4: visit_Compare
def visit_Compare (self, node):
self.generic_visit (node)
ans= node
# ls () < "bar.txt" > "foo.txt"
# Compare(left=Call(func=Name(id='ls', ctx=Load()), args=[], keywords=[],
# starargs=None, kwargs=None),
# ops=[Lt(), Gt()],
# comparators=[Str(s='bar.txt'), Str(s='foo.txt')]))
if is_executable (node.left):
# yes, they're reversed, but it makes more sense to me like this
for comp, op in zip (node.ops, node.comparators):
if type (comp)==Gt:
# > means _out
update_keyword (node.left, keyword (arg='_out', value=op))
ans= node.left
elif type (comp)==GtE:
# >= means _out+_err
update_keyword (node.left, keyword (arg='_out', value=op))
update_keyword (node.left, keyword (arg='_err_to_out', value=op))
ans= node.left
elif type (comp)==Lt:
# < means _in
update_keyword (node.left, keyword (arg='_in', value=op))
ans= node.left
return ans
示例5: visit_BinOp
def visit_BinOp(self, node):
if node.op.__class__ in self.operators:
sympy_class = self.operators[node.op.__class__]
right = self.visit(node.right)
if isinstance(node.op, ast.Sub):
right = ast.UnaryOp(op=ast.USub(), operand=right)
elif isinstance(node.op, ast.Div):
right = ast.Call(
func=ast.Name(id='Pow', ctx=ast.Load()),
args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
starargs=None,
kwargs=None
)
new_node = ast.Call(
func=ast.Name(id=sympy_class, ctx=ast.Load()),
args=[self.visit(node.left), right],
keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
starargs=None,
kwargs=None
)
if sympy_class in ('Add', 'Mul'):
# Denest Add or Mul as appropriate
new_node.args = self.flatten(new_node.args, sympy_class)
return new_node
return node
示例6: visit_Call
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and isinstance(node.func.ctx, ast.Load):
if node.func.id in map(lambda x: x.value, list(TradingCommands)):
parser = LocationPatcher(node)
node.keywords.append(parser.visit(ast.keyword(arg="lineno", value=ast.Num(n=node.lineno))))
node.keywords.append(parser.visit(ast.keyword(arg="col_offset", value=ast.Num(n=node.col_offset))))
return node
示例7: visit_Call
def visit_Call(self, node, parent):
if node in self.seen:
return node
self.seen.add(node)
callName = dict(ast.iter_fields(dict(ast.iter_fields(node))['func'])).get('id', None)
callType = dict(ast.iter_fields(dict(ast.iter_fields(node))['func'])).get('attr',None)
#print ast.dump(dict(ast.iter_fields(node))['func']), callType, node.lineno, node.col_offset
#print callName, self.localFuncs
if callName in self.localFuncs:
#print ast.dump(node)
#print callName, node.lineno, node.col_offset
dict(ast.iter_fields(node))['keywords'].append(ast.keyword(arg=self.calleeInfo, value=ast.Str(s=str(node.lineno) + "-" + str(node.col_offset))))
if callType in erps.keys() or callType == "stocPrim":
if callType not in self.primsNumArgs:
self.primsNumArgs[callType] = len(inspect.getargspec(globals()[callType]).args)
namedArgs = map(lambda x: dict(ast.iter_fields(x))['arg'], dict(ast.iter_fields(node))['keywords'])
numArgs = len(namedArgs) + len(dict(ast.iter_fields(node))['args'])
#print callType, node.lineno, node.col_offset
#print ast.dump(parent)
if not ('name' in namedArgs or numArgs == self.primsNumArgs[callType]): #check if name already supplied
dict(ast.iter_fields(node))['keywords'].append(ast.keyword(arg='name', value=ast.BinOp(left=ast.BinOp(left=ast.Call(func=ast.Name(id='str', ctx=ast.Load()), args=[ast.Name(id=self.funcStack, ctx=ast.Load())], keywords=[], starargs=None, kwargs=None), op=ast.Add(), right=ast.Call(func=ast.Name(id='str', ctx=ast.Load()), args=[ast.Name(id=self.locStack, ctx=ast.Load())], keywords=[], starargs=None, kwargs=None)), op=ast.Add(), right=ast.BinOp(left=ast.Str(s=str(node.lineno) + "-" + str(node.col_offset)), op=ast.Add(), right=ast.Call(func=ast.Name(id='str', ctx=ast.Load()), args=[ast.Name(id=self.loopStack, ctx=ast.Load())], keywords=[], starargs=None, kwargs=None)))))
ast.fix_missing_locations(node)
#print map(ast.dump, dict(ast.iter_fields(node))['keywords'])
self.generic_visit(node)
return node
示例8: visit_Compare
def visit_Compare (self, node):
self.generic_visit (node)
ans= node
# ls () < "bar.txt" > "foo.txt"
# Compare(left=Call(func=Name(id='ls', ctx=Load()), args=[], keywords=[],
# starargs=None, kwargs=None),
# ops=[Lt(), Gt()],
# comparators=[Str(s='bar.txt'), Str(s='foo.txt')]))
if self.is_executable (node.left):
# yes, they're reversed, but it makes more sense to me like this
for comp, op in zip (node.ops, node.comparators):
if type (comp)==Gt:
# > means _out
node.left.keywords.append (keyword (arg='_out', value=op))
ans= node.left
elif type (comp)==Lt:
# < means _in
# now, _in works differently
# a string is written directly to the stdin,
# instead of creating a file() with that name
# so, we do it ourseleves.
if type (op)==Str:
op= Call (func=Name (id='open', ctx=Load ()), args=[op],
keywords=[], starargs=None, kwargs=None)
node.left.keywords.append (keyword (arg='_in', value=op))
ast.fix_missing_locations (node.left)
ans= node.left
return ans
示例9: visit_FunctionDef
def visit_FunctionDef(self, node):
writer.write('def %s(args, kwargs):' % node.name)
writer.push()
# new pythonjs' python function arguments handling
# create the structure representing the functions arguments
# first create the defaultkwargs JSObject
writer.write('var(signature, arguments)')
L = len(node.args.defaults)
kwargsdefault = map(lambda x: keyword(self.visit(x[0]), x[1]), zip(node.args.args[-L:], node.args.defaults))
kwargsdefault = Call(
Name('JSObject', None),
[],
kwargsdefault,
None,
None
)
args = Call(
Name('JSArray', None),
map(lambda x: Str(x.id), node.args.args),
[],
None,
None
)
keywords = list([
keyword(Name('kwargs', None), kwargsdefault),
keyword(Name('args', None), args),
])
if node.args.vararg:
keywords.append(keyword(Name('vararg', None), Str(node.args.vararg)))
if node.args.kwarg:
keywords.append(keyword(Name('varkwarg', None), Str(node.args.kwarg)))
prebody = list()
# create a JS Object to store the value of each parameter
signature = ', '.join(map(lambda x: '%s=%s' % (self.visit(x.arg), self.visit(x.value)), keywords))
writer.write('signature = JSObject(%s)' % signature)
writer.write('arguments = get_arguments(signature, args, kwargs)')
# # then for each argument assign its value
for arg in node.args.args:
writer.write("""JS("var %s = arguments['%s']")""" % (arg.id, arg.id))
if node.args.vararg:
writer.write("""JS("var %s arguments['%s']")""" % (node.args.vararg, node.args.vararg))
# turn it into a list
expr = '%s = get_attribute(list, "__call__")(create_array(%s), {});'
expr = expr % (node.args.vararg, node.args.vararg)
writer.write(expr)
if node.args.kwarg:
writer.write("""JS('var %s = arguments["%s"]')""" % (node.args.kwarg, node.args.kwarg))
expr = '%s = get_attribute(dict, "__call__")(create_array(%s), {});'
expr = expr % (node.args.kwarg, node.args.kwarg)
writer.write(expr)
map(self.visit, node.body)
writer.pull()
# apply decorators
for decorator in reversed(node.decorator_list):
writer.write('%s = %s(create_array(%s))' % (node.name, self.visit(decorator), node.name))
示例10: make_argparse_arguments
def make_argparse_arguments(self):
for arg, name, help, action in self.macro_handler.args:
expr = ast.parse('parser.add_argument()').body[0]
expr.value.args = [ast.Str(arg)]
expr.value.keywords = [
ast.keyword('dest', ast.Str(name)),
ast.keyword('action', ast.Str(action)),
ast.keyword('help', ast.Str(help)),
]
yield expr
示例11: nameAndArgsToKeyword
def nameAndArgsToKeyword(name, args):
if name in groupbySet:
arg = 'groupby'
keyword = ast.keyword(arg=arg, value = ast.Dict(keys=args, values=args))
elif name in aggregationSet:
arg = 'aggregate'
keyword = ast.keyword(arg=arg, value = ast.Dict(keys=[ast.Str(name),], values=[ast.List(elts=args)]))
else:
raise NotImplementedError
return keyword
示例12: test_call
def test_call(self):
func = ast.Name("x", ast.Load())
args = [ast.Name("y", ast.Load())]
keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
self.expr(call, "must have Load context")
call = ast.Call(func, [None], keywords)
self.expr(call, "None disallowed")
bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
call = ast.Call(func, args, bad_keywords)
self.expr(call, "must have Load context")
示例13: test_wildcard_call_mixed_args
def test_wildcard_call_mixed_args(self):
pat = prepare_pattern("f(1, ??, a=2, **{'b':3})")
assert isinstance(pat.args, listmiddle)
assert_ast_like(pat.args.front[0], ast.Num(n=1))
assert not hasattr(pat, 'starargs')
assert isinstance(pat.keywords, types.FunctionType)
kwargs_dict = ast.Dict(keys=[ast.Str(s='b')], values=[ast.Num(n=3)])
if sys.version_info < (3, 5):
assert_ast_like(pat.kwargs, kwargs_dict)
else:
pat.keywords([ast.keyword(arg=None, value=kwargs_dict),
ast.keyword(arg='a', value=ast.Num(n=2))], [])
示例14: test_pos_final_wildcard
def test_pos_final_wildcard(self):
apf = ASTPatternFinder(prepare_pattern("f(1, ??)"))
it = apf.scan_ast(self.ast)
assert_ast_like(next(it), ast.Call(args=[ast.Num(n=1)]))
assert_ast_like(next(it), ast.Call(args=[ast.Num(n=1), ast.Num(n=2)]))
assert_ast_like(next(it), ast.Call(starargs=ast.Name(id='c')))
assert_ast_like(next(it), ast.Call(args=[ast.Num(n=1)],
keywords=[ast.keyword(arg='d'),
ast.keyword(arg='e'),
])
)
assert_ast_like(next(it), ast.Call(kwargs=ast.Name(id='k')))
self.assert_no_more(it)
示例15: create_super_call
def create_super_call(self, node):
super_call = utils.create_ast('super().{}()'.format(node.name)).body[0]
for arg in node.args.args[1:-len(node.args.defaults) or None]:
super_call.value.args.append(ast.Name(id=arg.arg, ctx=ast.Load()))
for arg, default in zip(node.args.args[-len(node.args.defaults):], node.args.defaults):
super_call.value.keywords.append(ast.keyword(arg=arg.arg, value=default))
for arg, default in zip(node.args.kwonlyargs, node.args.kw_defaults):
super_call.value.keywords.append(ast.keyword(arg=arg.arg, value=default))
if node.args.vararg:
super_call.value.starargs = ast.Name(id=node.args.vararg, ctx=ast.Load())
if node.args.kwarg:
super_call.value.kwargs = ast.Name(id=node.args.kwarg, ctx=ast.Load())
return super_call