Help me dig my way out of nested scoping

Terry Hancock hancock at anansispaceworks.com
Sun Apr 3 19:06:18 EDT 2005


On Sunday 03 April 2005 04:12 pm, Brendan wrote:
> from ThirdPartyLibrary import F
> from MyOtherModule import AB
> 
> def FW(x):
>     lastX = None
>     aLastX = None
>     bLastX = None

I'm pretty sure your method will work if you just specify
that these are global:

def FW(x):
    global lastX = None
    global aLastX = None
    global bLastX = None

OTOH, I'm biased against using module-level variables
for this kind of purpose and I think things that retain
state really ought to be class instances, so I'd probably replace
AB(x)  with a callable object, and define two wrappers to access it
(untested):

class AB:
    def __init__(self):
         self._last_x = None
         self._last_a = None
         self._last_b = None

    def __call__(self, x):
         if x == self._last_x:
             return self._last_a, self._last_b
         else:
             self._last_a, self._last_b = self.AB(x)
             return self._last_a, self._last_b

    def  A(self, x):
          return self(x)[0]

    def B(self, x):
         return self(x)[1]

    def AB(self, x):
         """
         This is where you compute your new values when needed.
         """
         # something that computes a and b
         return a,b

ab = AB()

Then you actually pass the methods ab.A and ab.B to your
library routine.  This will usually work, though if it somehow
insists on an actual function instead of a callable, you can always
use wrapper functions.

This also has the advantage that you *can* process more than
one case at a time (i.e. if you have two different places where you
need this function to be called and you aren't sure what order
they'll be processed (or don't want to think about it), you can
give them different instances of AB to work with, and they'll
remember their previous calls separately.

Cheers,
Terry


-- 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list