Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Standard Optional Argument Defaults

I have two functions:

def f(a,b,c=g(b)):
    blabla

def g(n):
    blabla

c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?

Someone suggested:

def g(b):
    blabla

def f(a,b,c=None):
    if c is None:
        c = g(b)
    blabla

But this doesn't work. Maybe the user intended c to be None and then c will have another value.

like image 557
ooboo Avatar asked Nov 28 '22 04:11

ooboo


2 Answers

def f(a,b,c=None):
    if c is None:
        c = g(b)

If None can be a valid value for c then you do this:

sentinel = object()
def f(a,b,c=sentinel):
    if c is sentinel:
        c = g(b)
like image 78
Paolo Bergantino Avatar answered Dec 10 '22 15:12

Paolo Bergantino


You cannot do it that way.

Inside the function, check if c is specified. If not, do the calculation.

def f(a,b,c=None):
    if c == None:
        c = g(b)
    blabla
like image 27
codeape Avatar answered Dec 10 '22 14:12

codeape