Home > Net >  Python: default value of function as a function argument
Python: default value of function as a function argument

Time:03-01

Suppose I have the function:

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

and let's say that I want a default value for b to be a-1.

If I write:

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

I get 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?

CodePudding user response:

You can do the following:

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

CodePudding user response:

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)

CodePudding user response:

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
  • Related