Easier way to save result of a function?

Ant antroy at gmail.com
Wed Jul 5 05:04:42 EDT 2006


> Thanks, that's awesome! Definitely not something I'd have ever been able
> to work out myself - I think I need to learn more about nested functions
> and introspection.

I've recently found nested functions incredibly useful in many places
in my code, particularly as a way of producing functions that are
pre-set with some initialization data. I've written a bit about it
here: http://antroy.blogspot.com/ (the entry about Partial Functions)

> > def memoizeMethod(cls, n, m):
> >   def decorated(self):
> >     if n in self._memo: return self._memo[n]
> >     result = self._memo[n] = m(self)
> >     return result
> >   decorated.__name__ = n
> >   setattr(cls, n, decorated)

Couldn't this be more simply written as:

 def memoizeMethod(cls, n, m):
   def decorated(self):
     if not n in self._memo:
          self._memo[n] = m(self)
     return self._memo[n]
   decorated.__name__ = n
   setattr(cls, n, decorated)

I've not seen the use of chained = statements before. Presumably it
sets all variables to the value of the last one?




More information about the Python-list mailing list