Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with dependent preset arguments

Tags:

python

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?

like image 459
theta Avatar asked Feb 02 '23 09:02

theta


1 Answers

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).

like image 50
NPE Avatar answered Feb 12 '23 00:02

NPE