I have a function with two optional parameters:
def func(a=0, b=10): return a+b
Somewhere else in my code I am doing some conditional argument passing like:
if a and b: return func(a, b) elif a: return func(a) elif b: return func(b=b) else: return func()
Is there anyway to simplify code in this pattern?
EDIT:
Let's assume that I'm not allowed to implement default parameter logic inside func
.
I may have several functions like func
: func1
, func2
and func3
would all contain the
a = a or 0 b = b or 10
statements.
But I'm invoking these series of functions to eliminate duplication. (using a decorator)
Many times you need to pass arguments to your Python scripts. Python provides access to these arguments through the sys module. You can directly access the argv functionality and handle the parse of arguments in your own, or you can use some other module as argparse that does that for you.
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
By default, arguments may be passed to a Python function either by position or explicitly by keyword.
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
If you don't want to change anything in func
then the sensible option would be passing a dict of arguments to the function:
>>> def func(a=0,b=10): ... return a+b ... >>> args = {'a':15,'b':15} >>> func(**args) 30 >>> args={'a':15} >>> func(**args) 25 >>> args={'b':6} >>> func(**args) 6 >>> args = {} >>> func(**args) 10
or just:
>>>func(**{'a':7}) 17
Going by the now-deleted comments to the question that the check is meant to be for the variables being None
rather than being falsey, change func
so that it handles the arguments being None
:
def func(a=None, b=None): if a is None: a = 0 if b is None: b = 10
And then just call func(a, b)
every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With