Optional Parameters, Certain Combination Of Them Required
Solution 1:
You could just use the keyword args dict:
deffunc(a, b, **kwargs):
valid_args = len(kwargs) == 1and ('c'in kwargs or'd'in kwargs)
ifnot valid_args:
return"Hey, provide exactly 1 of 'c' and 'd'"if'c'in kwargs:
# stuff to do if c is providedelif'd'in kwargs:
# stuff to do if d is provided
Solution 2:
I would say the easiest way for your user in your simple case is to refactor to separate functions. Each function does the different work as described and then a common one e.g. for your last case
def funcC(a, b, c):
# stuff todoif c is provided, with e as c
common_func(a,b,c, None)
def funcD(a, b, d):
# stuff todoif d is provided, with e as d
common_func(a,b,None, d)
The user then knows what parameters matter and only the valid possible combinations can be used, the user does not have to guess or have a chance to call them incorrectly. You as providing the function can provide whatever is needed for the parameter the caller does not supply.
There are longer explanations of these found by googling for "flag parameters" e.g. Martin FowlerStack Overflow these tend to mention Boolean arguments but this in effect the same thing a different code path depending on a parameter which has no other effect.
Another phrase to look for is "control coupling"
Solution 3:
Here is another one, which will allow the arguments be specified, and differentiates between c=None
and c
not given, while still providing the argument names explicitly:
undefined = object()
def func(a, b, c=undefined, d=undefined):
if (c is undefined) ^ (d is undefined):
raise TypeError("Hey, provide exactly 1 of 'c' and 'd'")
...
On Python 3, keyword only arguments make it even nicer, making sure that the caller explicitly specifies c
or d
:
def func(a, b, *, c=undefined, d=undefined):
if (c is undefined) ^ (d is undefined):
raise TypeError("Hey, provide exactly 1 of 'c' and 'd'")
Post a Comment for "Optional Parameters, Certain Combination Of Them Required"