full closures

Steven Majewski sdm7g at Virginia.EDU
Wed Feb 27 16:25:07 EST 2002



> "Michael P. Soulier" <msoulier at nortelnetworks.com_.nospam> wrote in
> message news:slrna7q9m0.4pb.msoulier at pmerd071.ca.nortel.com...
> >     While I know about bound methods in Python, I'm wondering if a
> > full closure can be implemented. Can it?
> >

Python is *FULL* of ways to build closures:
	class instances
	exec expr in dict
	new.function( oldfunc.func_code, globals )
	generators
	... and maybe a few more I haven't though of.

Which to choose depends on what you need to do.
( What *do* you need to do ? )

On Wed, 27 Feb 2002, Terry Reedy wrote:
>
> Default arg works as long as function is called properly:
>
> >>> def prcnt(counter = [0]):
> ...   print "The current count is %d" % counter[0]
> ...   counter[0] = counter[0] + 1
> ...

However, I wouldn't count Terry's method (above) among them.

A closure is a expression + environment|bindings, but I think
it's implicit in the definition that the two are independent,
and you can easily construct a new closure with a different
set of bindings.

You *could* use new.function to build one with a different default
value, but those values are by position rather than the by-name
globals dict, so that seems more awkward than
	 new.function( func.func_code, newGlobals )

By itself, I'ld just call the above an example of python's strange
syntax for a local static variable.


-- Steve Majewski






More information about the Python-list mailing list