Another dumb scope question for a closure.

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 15:55:15 EST 2008


Ben Fisher wrote:

> One way to get this to work is:
> 
> def inc(jj):
> 	def dummy(jj = jj):
> 		jj = jj + 1
> 		return jj
> 	return dummy
> 
> h = inc(33)
> print h()
> 
> It's not very pretty though, especially when you have many variables
> you want to have in the inner scope.

Default argument binding allows you to bind to an outer object rather 
than a name, but it doesn't help if you want to update the object:

 >>> def inc(jj):
...     def dummy(jj = jj):
...             jj = jj + 1
...             return jj
...     return dummy
...
 >>> h = inc(33)
 >>> print h()
34
 >>> print h()
34
 >>> print h()
34
 >>> print h()
34

</F>




More information about the Python-list mailing list