Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: default value of function as a function argument

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?

like image 595
Kώστας Κούδας Avatar asked Jul 21 '26 08:07

Kώστας Κούδας


2 Answers

You can do the following:

def myF(a, b=None):
    if b is None:
        b = a - 1
    return a * b - 2 * b
like image 165
Selcuk Avatar answered Jul 24 '26 07:07

Selcuk


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
like image 22
James Avatar answered Jul 24 '26 07:07

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!