Reputation: 952
I realize this might be a somewhat strange request, but I'd like to have a method accept an arbitrary amount of tuples in Python 3, each tuple with default parameters.
The reason I'd like to do this is because I'm writing scripting functionality for our group, and want callable methods for users to be easy to understand. For example, if the user wants to call a 2D plotting method, I want the method arguments to look like this:
plot2D(('sweepvar1', start1, stop1, npts1=None, step1=None),
('sweepvar2', start2, stop2, npts2=None, step2=None))
So the user calls something like this
plot2D(('var1', 0.0, 1.0, npts1=101), ('var2', 0.5, 0.6, step2=0.001))
Essentially the difficulty is coming because I don't know apriori if the user wants to specify a number of points or a step size for the measurement, but we need to include both options. Ideally I want to avoid forcing users to specify both, or create a new variable that is a flag for choosing between npts
and step
.
I am somewhat familiar with default parameters
, *args
, and **kwargs
, but I can't seem to come up with a clean solution to the above problem.
Thanks in advance for the help!
Upvotes: 1
Views: 568
Reputation: 140307
That seems difficult to achieve as-is, but you could create an helper function which wraps the arguments and creates a tuple of positional & keyword args for each tuple. Call that mkarg
(make argument)
def mka(*args,**kwargs):
return (args,kwargs)
def plot2D(t1,t2):
print(t1,t2)
plot2D(mka('var1', 0.0, 1.0, npts1=101), mka('var2', 0.5, 0.6, step2=0.001))
this test returns:
(('var1', 0.0, 1.0), {'npts1': 101}) (('var2', 0.5, 0.6), {'step2': 0.001})
now the tedious work is to process those arguments in plot2D
, but at least users have a clear interface.
Alternative:
if you really want tuples, you could check the len
of your tuple parameters, and complete with None
if not long enough. That's good if the second "optional" value is less used than the first. Practical for a small amount of "optional" values.
def plot2D(tuple1,tuple2):
tuple1 += (None,)*(5-len(tuple1))
tuple2 += (None,)*(5-len(tuple2))
plot2D(('var1', 0.0, 1.0, 101), ('var2', 0.5, 0.6, None, 0.001))
Upvotes: 2