I need some help with figuring out Pythons *args and **kwargs. It’s simple but I haven’t entire wrapped my head around them. Here’s one of scenarios that’s bewildering to me.
I have two functions mainfunc and wrapperfunc (which is a wrapper function for the main function). It looks like this.
def mainfunc(fname=None, lname=None):
print 'Firstname: ' + fname
print 'Lastname: ' + lname
def wrapperfunc(uname, *args):
print uname
mainfunc(*args)
I can call wrapperfunc like this:
wrapperfunc('j.doe', 'john', 'doe')
In this method, all three parameters are positional. Since j.doe comes into uname, the other two params can be accessed by *args
..but is it possible to pass some of the params to wrapperfunc from a dict so that I can still access uname inside wrapperfunc directly and then pass the remaining positional parameters to the mainfunc. Something like the following snippet:
params = {'uname':'j.doe'}
wrapperfunc(**params, 'john', 'doe')
I want to access the named parameters directly inside wrapperfunc but pass all the positional parameters to mainfunc.
Keyword arguments must come after position arguments in Python.
will pass the keyword arguments after the two positional arguments,
If you want to look at an argument, but otherwise do the call normally, do:
You can generalize this to work on any function you want as a decorator.