Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the default value of an argument depend on another argument (in Python)?

For instance, I want:

def func(n=5.0,delta=n/10):

If the user has specified a delta, use it. If not, use a value that depends on n. Is this possible?

like image 222
elexhobby Avatar asked Feb 15 '14 22:02

elexhobby


People also ask

Can you set default values to Python arguments?

In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions.

How do you pass a default argument to a function in Python?

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=).

How will you specify a default value for an argument in the function definition?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value. Let's understand this through a function student.

Can we give default value to arguments?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


4 Answers

The language doesn't support such syntax.

The usual workaround for these situations(*) is to use a default value which is not a valid input.

def func(n=5.0, delta=None):
     if delta is None:
         delta = n/10

(*) Similar problems arise when the default value is mutable.

like image 65
Karoly Horvath Avatar answered Oct 04 '22 13:10

Karoly Horvath


You can't do it in the function definition line itself, you need to do it in the body of the function:

def func(n=5.0,delta=None):
    if delta is None:
        delta = n/10
like image 27
BrenBarn Avatar answered Oct 04 '22 13:10

BrenBarn


You could do:

def func(n=5.0, delta=None):
    if delta is None:
        delta = n / 10
    ...
like image 30
jonrsharpe Avatar answered Oct 04 '22 11:10

jonrsharpe


These answers will work in some cases, but if your dependent argument (delta) is a list or any iterable data type, the line

    if delta is None:

will throw the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If your dependent argument is a dataframe, list, Series, etc, the following lines of code will work better. See this post for the idea / more details.

    def f(n, delta = None):
        if delta is f.__defaults__[0]:
            delta = n/10
like image 24
baileyw Avatar answered Oct 04 '22 11:10

baileyw