Closures
Mark McEahern
marklists at mceahern.com
Thu Apr 29 20:30:16 EDT 2004
On Thu, 2004-04-29 at 17:17, Michael Sparks wrote:
> On Thu, 29 Apr 2004, Gustavo Niemeyer wrote:
>
> > class Closure:
> > def __init__(self):
> > self.__dict__ = sys._getframe().f_back.f_locals
>
> Out of interest how portable is this? Strikes me as extremely useful
> class to have lying around :) The only thing that makes me wonder is the
> access to _getframe...
There are more straightforward ways to get at locals--here's a modified
version that uses doctest to demonstrate/prove what the code does. Is
the value of Closure--beyond just plain old nested scopes--that you
don't have to pass counter into getFunc()?
#!/usr/bin/env python
import doctest
import unittest
class Closure:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def getFunc():
"""
>>> c = getFunc()
>>> c()
1
>>> c()
2
>>> c()
3
"""
counter = 0
c = Closure(**locals())
def count():
c.counter += 1
print c.counter
return count
def test_suite():
return doctest.DocTestSuite()
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
More information about the Python-list
mailing list