本文整理汇总了Python中ast.arguments方法的典型用法代码示例。如果您正苦于以下问题:Python ast.arguments方法的具体用法?Python ast.arguments怎么用?Python ast.arguments使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.arguments方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_AST_objects
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def test_AST_objects(self):
x = ast.AST()
self.assertEqual(x._fields, ())
with self.assertRaises(AttributeError):
x.vararg
with self.assertRaises(AttributeError):
x.foobar = 21
with self.assertRaises(AttributeError):
ast.AST(lineno=2)
with self.assertRaises(TypeError):
# "_ast.AST constructor takes 0 positional arguments"
ast.AST(2)
示例2: test_nodeclasses
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def test_nodeclasses(self):
# IronPyhon performs argument typechecking
l=ast.Str('A')
o=ast.Mult()
r=ast.Num('13')
x=ast.BinOp(l,o,r,lineno=42)
self.assertEqual(x.left, l)
self.assertEqual(x.op, o)
self.assertEqual(x.right, r)
self.assertEqual(x.lineno, 42)
# node raises exception when not given enough arguments
self.assertRaises(TypeError, ast.BinOp, l, o)
# can set attributes through kwargs too
x = ast.BinOp(left=l, op=o, right=r, lineno=42)
self.assertEqual(x.left, l)
self.assertEqual(x.op, o)
self.assertEqual(x.right, r)
self.assertEqual(x.lineno, 42)
# this used to fail because Sub._fields was None
x = ast.Sub()
示例3: _check_specific_to_fields
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def _check_specific_to_fields(self, name):
# these tests don't apply for the typename, just the fieldnames
if name in self.seen_fields:
raise ValueError('Encountered duplicate field name: '
'{0!r}'.format(name))
if name.startswith('_'):
raise ValueError('Field names cannot start with an underscore: '
'{0!r}'.format(name))
########################################################################
# Returns a function with name 'name', that calls another function 'chain_fn'
# This is used to create the __init__ function with the right argument names and defaults, that
# calls into _init to do the real work.
# The new function takes args as arguments, with defaults as given.
示例4: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def visit_Call(self, node: ast.Call) -> Any:
"""Visit the function and the arguments and finally make the function call with them."""
func = self.visit(node=node.func)
args = [] # type: List[Any]
for arg_node in node.args:
if isinstance(arg_node, ast.Starred):
args.extend(self.visit(node=arg_node))
else:
args.append(self.visit(node=arg_node))
kwargs = dict() # type: Dict[str, Any]
for keyword in node.keywords:
if keyword.arg is None:
kw = self.visit(node=keyword.value)
for key, val in kw.items():
kwargs[key] = val
else:
kwargs[keyword.arg] = self.visit(node=keyword.value)
result = func(*args, **kwargs)
self.recomputed_values[node] = result
return result
示例5: parse_nni_variable
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def parse_nni_variable(code):
"""Parse `nni.variable` expression.
Return the name argument and AST node of annotated expression.
code: annotation string
"""
name, call = parse_annotation_function(code, 'variable')
assert len(call.args) == 1, 'nni.variable contains more than one arguments'
arg = call.args[0]
assert type(arg) is ast.Call, 'Value of nni.variable is not a function call'
assert type(arg.func) is ast.Attribute, 'nni.variable value is not a NNI function'
assert type(arg.func.value) is ast.Name, 'nni.variable value is not a NNI function'
assert arg.func.value.id == 'nni', 'nni.variable value is not a NNI function'
name_str = astor.to_source(name).strip()
keyword_arg = ast.keyword(arg='name', value=ast.Str(s=name_str))
arg.keywords.append(keyword_arg)
if arg.func.attr == 'choice':
convert_args_to_dict(arg)
return name, arg
示例6: visit_arguments
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def visit_arguments(self, node):
extra_args = [self._make_arg(node.vararg),
[self._make_arg(n) for n in node.kwonlyargs],
self._visit(node.kw_defaults),
self._make_arg(node.kwarg),
self._visit(node.defaults), ]
if sys.version_info.minor >= 8:
new_node = ast.arguments(
[self._make_arg(arg) for arg in node.posonlyargs],
[self._make_arg(n) for n in node.args],
*extra_args
)
else:
new_node = ast.arguments(
[self._make_arg(n) for n in node.args],
*extra_args
)
return new_node
示例7: make_function_arguments
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def make_function_arguments(args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations):
"""
Make an ast.arguments from the args parsed out of a code object.
"""
return ast.arguments(
args=[ast.arg(arg=a, annotation=annotations.get(a)) for a in args],
kwonlyargs=[
ast.arg(arg=a, annotation=annotations.get(a)) for a in kwonly
],
defaults=defaults,
kw_defaults=list(map(kw_defaults.get, kwonly)),
vararg=None if varargs is None else ast.arg(
arg=varargs, annotation=annotations.get(varargs),
),
kwarg=None if varkwargs is None else ast.arg(
arg=varkwargs, annotation=annotations.get(varkwargs)
),
)
示例8: arguments
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def arguments(_, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults): # noqa
return _ast.arguments(args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) # noqa
示例9: def_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def def_rewrite(mark: Tokenizer,
name: Tokenizer,
args: ast.arguments,
ret: ast.AST,
body: list,
is_async: bool = False):
name = name.value
ty = ast.AsyncFunctionDef if is_async else ast.FunctionDef
return ty(name, args, body, [], ret, **loc @ mark)
示例10: test_arguments
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
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)
示例11: test_compile_from_ast_128
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def test_compile_from_ast_128(self):
cap = StringIO()
tc = """
def f(a,*args):
return args[1]
print >> cap, f(1,2,42),
"""
p = ast.parse( tc, mode="exec") # call function with a variable number of arguments
c = compile(p,"<unknown>", mode="exec")
exec c
self.assertEquals(cap.getvalue(), "42")
示例12: _make_fn
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def _make_fn(name, chain_fn, args, defaults):
args_with_self = ['_self'] + list(args)
arguments = [_ast.Name(id=arg, ctx=_ast.Load()) for arg in args_with_self]
defs = [_ast.Name(id='_def{0}'.format(idx), ctx=_ast.Load()) for idx, _ in enumerate(defaults)]
if _PY2:
parameters = _ast.arguments(args=[_ast.Name(id=arg, ctx=_ast.Param()) for arg in args_with_self],
defaults=defs)
else:
parameters = _ast.arguments(args=[_ast.arg(arg=arg) for arg in args_with_self],
kwonlyargs=[],
defaults=defs,
kw_defaults=[])
module_node = _ast.Module(body=[_ast.FunctionDef(name=name,
args=parameters,
body=[_ast.Return(value=_ast.Call(func=_ast.Name(id='_chain', ctx=_ast.Load()),
args=arguments,
keywords=[]))],
decorator_list=[])])
module_node = _ast.fix_missing_locations(module_node)
# compile the ast
code = compile(module_node, '<string>', 'exec')
# and eval it in the right context
globals_ = {'_chain': chain_fn}
locals_ = dict(('_def{0}'.format(idx), value) for idx, value in enumerate(defaults))
eval(code, globals_, locals_)
# extract our function from the newly created module
return locals_[name]
########################################################################
# Produce a docstring for the class.
示例13: _nt_make
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def _nt_make(cls, iterable, new=tuple.__new__):
result = new(cls, iterable)
if len(result) != len(cls._fields):
raise TypeError('Expected {0} arguments, got {1}'.format(len(cls._fields), len(result)))
return result
示例14: visit_CallTrue
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
"""Generates python code calling the function and returning True.
lambda: fn(*args) or True
"""
return ast.Lambda(
ast.arguments([], None, None, [], None, None, [], []),
ast.BoolOp(
ast.Or(),
[
self.visit_Call(node),
ast.Name('True', ast.Load())]))
示例15: parserrule_topython
# 需要导入模块: import ast [as 别名]
# 或者: from ast import arguments [as 别名]
def parserrule_topython(parser: parsing.BasicParser,
rulename: str) -> ast.FunctionDef:
"""Generates code for a rule.
def rulename(self):
<code for the rule>
return True
"""
visitor = RuleVisitor()
rule = parser._rules[rulename]
fn_args = ast.arguments([ast.arg('self', None)], None, None, [], None,
None, [], [])
body = visitor._clause(rule_topython(rule))
body.append(ast.Return(ast.Name('True', ast.Load())))
return ast.FunctionDef(rulename, fn_args, body, [], None)