Please consider simple function:
def fun(x, y, param1=10, param2=param1/3):
do something
Where param1
and param2
should not be required but can be set by user. If param2
is not set, value is dependant on param1
in some way.
Above example will raise NameError: name 'param1' is not defined
Is there a way to do this kind of assignment in Python?
One way is to emulate this inside the function:
def fun(x, y, param1=10, param2=None):
if param2 is None:
param2 = param1/3
# do something
If param2=None
is a valid input into fun()
, the following might be a better alternative:
default = object()
def fun(x, y, param1=10, param2=default):
if param2 is default:
param2 = param1 / 3
# do something
(Having been looking at this second example for a few minutes, I actually quite like the is default
syntax.)
The reason the original version doesn't work is that default values are computed and bound at the function definition time. This means that you can't have a default that's dependent on something that's not known until the function is called (in your case, the value of param1
).
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