Reputation: 3559
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
Upvotes: 2
Views: 148
Reputation: 1729
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
Upvotes: 3
Reputation: 56644
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
Upvotes: 1
Reputation: 137350
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
Upvotes: 1
Reputation: 113978
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
Upvotes: 1