Call a function: Difference between revisions

→‎{{header|Python}}: more on *args, **kwargs and so on.
(rearranges in order of the language.)
(→‎{{header|Python}}: more on *args, **kwargs and so on.)
Line 1,736:
 
=={{header|Python}}==
Under the hood all Python function/method parameters are named. All arguments can be passed as ''name=value'' pairs or as a dictionary containing such pairs using the ''myfunc('''**key_args''')'' (apply over dictionary) syntax). One can also "apply" a function over a sequence of arguments using the syntax: ''myfunc('''*args''')'' as noted in comments below. Parameters can be mixed so long parameters with default values (optional arguments) follow any "positional" (required) parameters, and catchall parameter ('''''*args''''') follow those, and any "keyword arguments' parameter" is last. (Any function can only have up to one "catchall" or '''''*args'''' parameter and up to one "keyword args" '''''**kwargs''''' parameter).
<lang python>def no_args():
pass
Line 1,745 ⟶ 1,746:
# call
fixed_args(1, 2) # x=1, y=2
 
## Can also called them using the parameter names, in either order:
fixed_args(y=2, x=1)
 
## Can also "apply" fixed_args() to a sequence:
myargs=(1,2) # tuple
fixed_args(*myargs)
 
def opt_args(x=1):
Line 1,778 ⟶ 1,786:
is_builtin(pow) # True
is_builtin(is_builtin) # False
 
# Very liberal function definition
 
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
# Passing those to another, wrapped, function:
wrapped_fn(*args, **kwargs)
# (Function being wrapped can have any parameter list
# ... that doesn't have to match this prototype)
 
## A subroutine is merely a function that has no explicit
Line 1,787 ⟶ 1,807:
## For partial function application see:
## http://rosettacode.org/wiki/Partial_function_application#Python</lang>
 
 
=={{header|R}}==
Anonymous user