Why read-only nested scopes?

Terry Reedy tjreedy at udel.edu
Thu Sep 5 09:24:03 EDT 2002


"Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message
> And don't forget that when the nested function is called the frame
object
> may no longer exist: nested scope variables can continue to exist
after the
> frame in which they were created has been destroyed.

Example:
>>> def adder(x):
...   def _(y):
...     return x+y
...   return _
...
>>> a5=adder(5)
>>> a5(7)
12

Here, adder is a factory that turns out callable instances.  It could
instead be written

>>> class adder:
...   def __init__(self,x):
...     self.x = x
...   def __call__(self,y):
...     return self.x + y
...
>>> a5=adder(5)
>>> a5(7)
12

If one want writable persistent variables, one can use the class
syntax, which also allows for writable class rather than instance
variables.

Terry J. Reedy






More information about the Python-list mailing list