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:
If
param2=Noneis a valid input intofun(), the following might be a better alternative:(Having been looking at this second example for a few minutes, I actually quite like the
is defaultsyntax.)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).