On 3 Apr 2005 14:12:48 -0700, "Brendan" <[EMAIL PROTECTED]> wrote:
>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. You have several easy choices, that would not require you modifying your program much. 1. Use the 'global' keyword to declare lastX, aLastX, and bLastX as globals, then all functions will have access to them. def FW(x): global lastX, aLastX, bLastX 2. Use function attributes, which are just names attached to the function using a '.'. def FW(x): # # Function body here # return F(AW, BW) FW.lastX = None FW.aLastX = None FW.bLastX = None result = FW(x) You will need to always include the FW. in front of those names. 3. Something else, that may help is you can return more than one value at a time. Python has this neat feature that you can have multiple items on either side of the '=' sign. a,b,c = 1,2,3 same as: a=1 b=2 c=3 And it also works with return statements so you can return multiple value. def abc(n): return n+1, n+2, n+3 a,b,c = abc(0) 5. Choice 5 and above is to rewrite your function as a class. Names in class's retain their values between calls and you can access those values the same way as accessing function attributes. Hope this helped. Cheers, Ron >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 -- http://mail.python.org/mailman/listinfo/python-list