Help me dig my way out of nested scoping

James Stroud jstroud at mbi.ucla.edu
Sun Apr 3 18:18:00 EDT 2005


I wish I had time to dig into your specific problem because it looks 
interesting. But I think you might want to look at "python generators". I 
beleive there is no reason that they can't yield a function.

http://www.python.org/peps/pep-0255.html
http://docs.python.org/ref/yield.html
http://linuxgazette.net/100/pramode.html

James

On Sunday 03 April 2005 02:12 pm, Brendan 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.
>
> 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
> --
> Brendan Simons

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list