2

How can I make a Python function default value be evaluated each time the function is called? Take this dummy code:

b=0
def a():
    global b
    return b

def c(d=a()):
    return d

What I would expect as output:

>>> c()
0
>>> b=1
>>> a()
1
>>> c()
1

What I actually get:

>>> c()
0
>>> b=1
>>> a()
1
>>> c()
0
4

4 回答 4

3

One more solution, in closer resemblance to your original answer.

b = 0
def a():
    return b

def c(d=a):    # When it's a parameter, the call will be evaluated and its return 
               # value will be used. Instead, just use the function name, because
    return d() # within the scope of the function, the call will be evaluated every time.

When a function name is paired with the parentheses and its parameters, like f(x), it is assumed your intention is to call it at that time

于 2012-09-23T23:56:30.520 回答
1

d=a() is evaluated at start of program when function c is defined (ie a() gets called while it returns 0 ...)

def c(d=None):
    if d == None: d=a()
    return d

will cause it to be evaluated at the time you want

于 2012-09-23T23:40:40.453 回答
1

The problem here is, as you probably already know, that the d=a() (default argument assignement) is evaluated when the function is defined.

To change that, it is pretty common to use eg. None as default argument and evaluate it in the body of the function:

b=0
def a():
    global b
    return b

def c(d=None):
    if d is None:
        d = a()
    return d
于 2012-09-23T23:41:18.310 回答
1

I'll give a slight variation on the above:

b = 0

def a():
    # unless you are writing changes to b, you do not have to make it a global
    return b

def c(d=None, get_d=a):
    if d is None:
        d = get_d()
    return d
于 2012-09-23T23:53:24.940 回答