7
def myF(a, b):
    return a*b-2*b

Let's say that I want a default value for b to be a-1:

def myF(a, b=a-1):
    return a*b-2*b

gets the error message:

NameError: name 'a' is not defined

I can use the code below:

def myF(a, b):
    return a*b-2*b

def myDefaultF(a):
    return myF(a, a-1)

to have myF with default value, but I don't like it.

How can I avoid myDefaultF and have myF with default value a-1 for b without errors?

1
  • 1
    Interestigly, you can do this with functions in JS and R. Commented Aug 11, 2023 at 22:40

3 Answers 3

11

You can do the following:

def myF(a, b=None):
    if b is None:
        b = a - 1
    return a * b - 2 * b
Sign up to request clarification or add additional context in comments.

Comments

3

If you need to have the value of b be a function of a, but you might need that function to change, you can set the default value of b to be a lambda function and then check if b is callable in the function block.

def myF(a, b=lambda a: a-1):
    if callable(b):
        b = b(a)
    return a * b - 2 * b

This allows you to set a different function for b on the fly as well.

# pass b as an integer
myF(1, 1)
# returns: -1


# use default function for b
myF(4)
# returns: 6


# set b to be 2*a + 1
myF(3, lambda a: 2*a+1)
# returns: 7

1 Comment

The lambda isn't important. What's important is detecting if b is a callable function.
-1

You can use a try-except clause:

def myF(a, b=None):
  try:
    return a*b-2*b
  except:
    return a*(a-1)-2*(a-1)

1 Comment

This is not a good practice to suggest as it's an abuse of the exception handling system. Besides a broad except clause will catch and silently suppress other errors, such as passing a non-numeric value for b. From The Zen of Python: "Explicit is better than implicit".

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.