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.
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)
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With