I have a function with one optional argument, like this:
def funA(x, a, b=1):
return a+b*x
I want to write a new function that calls funA
and also has an optional argument, but if no argument is passed, I want to keep the default in funA
.
I was thinking something like this:
def funB(x, a, b=None):
if b:
return funA(x, a, b)
else:
return funA(x, a)
Is there a more pythonic way of doing this?
Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.
As a guideline, you shouldn't use a default argument as a flag upon which to conditionally execute code. You should instead break the function into two or more overloaded functions if you can.
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
Default arguments can be skipped from function call.
I would replace if b
with if b is not None
, so that if you pass b=0
(or any other "falsy" value) as argument to funB
it will be passed to funA
.
Apart from that it seems pretty pythonic to me: clear and explicit. (albeit maybe a bit useless, depending on what you're trying to do!)
A little more cryptic way that relies on calling funB
with the correct keyword arguments (e.g. funB(3, 2, b=4)
:
def funB(x, a, **kwargs):
return funA(x, a, **kwargs)
def funA(x, a, b=1):
return a+b*x
def funB(x, a, b=1):
return funA(x, a, b)
Make the default value of b=1
in funB()
and then pass it always to funA()
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