elexhobby
elexhobby

Reputation: 2668

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?

Upvotes: 35

Views: 12338

Answers (4)

baileyw
baileyw

Reputation: 99

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

Upvotes: 4

Karoly Horvath
Karoly Horvath

Reputation: 96258

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.

Upvotes: 43

BrenBarn
BrenBarn

Reputation: 251365

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

Upvotes: 5

jonrsharpe
jonrsharpe

Reputation: 121975

You could do:

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

Upvotes: 2

Related Questions