B
Brendan
Hi everyone
I'm new to Python, so forgive me if the solution to my question should
have been obvious. I have a function, call it F(x), which asks for two
other functions as arguments, say A(x) and B(x). A and B are most
efficiently evaluated at once, since they share much of the same math,
ie, A, B = AB(x), but F wants to call them independantly (it's part of
a third party library, so I can't change this behaviour easily). My
solution is to define a wrapper function FW(x), with two nested
functions, AW(x) and BW(x), which only call AB(x) if x has changed.
To make this all clear, here is my (failed) attempt:
#------begin code ---------
from ThirdPartyLibrary import F
from MyOtherModule import AB
def FW(x):
lastX = None
aLastX = None
bLastX = None
def AW(x):
if x != lastX:
lastX = x
# ^ Here's the problem. this doesn't actually
# change FW's lastX, but creates a new, local lastX
aLastX, bLastX = AB(x)
return aLastX
def BW(x):
if x != lastX:
lastX = x
# ^ Same problem
aLastX, bLastX = AB(x)
return bLastX
#finally, call the third party function and return its result
return F(AW, BW)
#-------- end code ---------
OK, here's my problem: How do I best store and change lastX, A(lastX)
and B(lastX) in FW's scope? This seems like it should be easy, but I'm
stuck. Any help would be appreciated!
-Brendan
I'm new to Python, so forgive me if the solution to my question should
have been obvious. I have a function, call it F(x), which asks for two
other functions as arguments, say A(x) and B(x). A and B are most
efficiently evaluated at once, since they share much of the same math,
ie, A, B = AB(x), but F wants to call them independantly (it's part of
a third party library, so I can't change this behaviour easily). My
solution is to define a wrapper function FW(x), with two nested
functions, AW(x) and BW(x), which only call AB(x) if x has changed.
To make this all clear, here is my (failed) attempt:
#------begin code ---------
from ThirdPartyLibrary import F
from MyOtherModule import AB
def FW(x):
lastX = None
aLastX = None
bLastX = None
def AW(x):
if x != lastX:
lastX = x
# ^ Here's the problem. this doesn't actually
# change FW's lastX, but creates a new, local lastX
aLastX, bLastX = AB(x)
return aLastX
def BW(x):
if x != lastX:
lastX = x
# ^ Same problem
aLastX, bLastX = AB(x)
return bLastX
#finally, call the third party function and return its result
return F(AW, BW)
#-------- end code ---------
OK, here's my problem: How do I best store and change lastX, A(lastX)
and B(lastX) in FW's scope? This seems like it should be easy, but I'm
stuck. Any help would be appreciated!
-Brendan