python - Using variable length argument lists and named parameters together -



python - Using variable length argument lists and named parameters together -

i need help figuring out pythons *args , **kwargs. it's simple haven't entire wrapped head around them. here's 1 of scenarios that's bewildering me.

i have 2 functions mainfunc , wrapperfunc (which wrapper function main function). looks this.

def mainfunc(fname=none, lname=none): print 'firstname: ' + fname print 'lastname: ' + lname def wrapperfunc(uname, *args): print uname mainfunc(*args)

i can phone call wrapperfunc this:

wrapperfunc('j.doe', 'john', 'doe')

in method, 3 parameters positional. since j.doe comes uname, other 2 params can accessed *args

..but possible pass of params wrapperfunc dict can still access uname within wrapperfunc straight , pass remaining positional parameters mainfunc. next snippet:

params = {'uname':'j.doe'} wrapperfunc(**params, 'john', 'doe')

i want access named parameters straight within wrapperfunc pass positional parameters mainfunc.

keyword arguments must come after position arguments in python.

params = {'uname':'j.doe'} wrapperfunc('john', 'doe', **params)

will pass keyword arguments after 2 positional arguments,

if want @ argument, otherwise phone call normally, do:

def wrapper(*args, **kwargs): print kwargs["uname"] homecoming mainfunc(*args, **kwargs)

you can generalize work on function want decorator.

def wrapper(f): def wrapped(*args, **kwargs): print kwargs["uname"] homecoming mainfunc(*args, **kwargs) homecoming wrapped @wrapper def foo(uname="test"): homecoming uname + "bar" # @decorator equivalent `foo = wrapper(foo)`

python

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -