Python vs. Lisp: scope issues

Bengt Richter bokr at oz.net
Thu Oct 16 07:36:13 EDT 2003


On Tue, 14 Oct 2003 10:59:50 -0700, David Eppstein <eppstein at ics.uci.edu> wrote:

>In article <bmh8bf$f79$1 at news.peterlink.ru>,
> anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> wrote:
>
>> In addition to s[0] hack, I'd like to suggest the following code. Any 
>> comments are highly appreciated:
>> 
>> class Scope(object):
>>      pass
>> 
>> def accumulator():
>>      scope = Scope()
>>      scope.n = 0
>>      def f(n):
>>          scope.n += n
>>          return scope.n
>>      return f
>
>Definitely cleaner than the s[0] hack.  I'll have to remember that the 
>next time I need to work around the scope limitation.
>
I don't know if a little class isn't just as good, e.g., (I made it initializable, but that's
a nit).

  class Accumulator(object):
      __slots__ = ['n']
      def __init__(self, n=0): self.n = n
      def __call__(self, n): self.n +=n; return self.n

  a = Accumulator()


BTW, can you plug in a __slots__ in the class dict via a metaclass and have it take effect,
or is that too late? IWT you could, but the class body definition has already been executed
and its elements bound in a dict, so will that dict be converted after the metaclass mod
to a slotted version?

Regards,
Bengt Richter




More information about the Python-list mailing list