35

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?

2
  • 1
    Python doesn't support doing this directly in the arglist, unlike (say) R. The Python solution is typically to default to None (/np.nan/ np.NINF/np.PINF/etc.) and then have the function body compute the correct default. Commented May 8, 2018 at 10:29
  • This could be a useful addition to Python. Can you suggest this to the developers? Commented Apr 17, 2024 at 8:22

4 Answers 4

43

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Since this is canonical, you want to illustrate why Python messes up when the default value is mutable.
delta = delta if delta != None else n/10 for a one-liner
For non falsy values, I find delta = delta or n/10 to be more pleasing
@RadioControlled it's probably better to use delta is not None here (!= None won't always do quite what you expect).
5

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

Comments

4

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

1 Comment

upvoted. python is always harder to use than it could be. and i'm ten years into the language.
2

You could do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.