What are python closures realy like?

John Nagle nagle at animats.com
Tue Dec 12 02:19:07 EST 2006


Paul Boddie wrote:
> I know that everyone will say that Python is a "multi-paradigm"
> language and that one should feel free to use whatever technique seems
> appropriate to solve the problem at hand, but it seems to me that
> there's been an explosion in nested function usage recently, with lots
> of code snippets showing them off either in the context of a debugging
> exercise or as a proposed solution to a problem, and yet in many cases
> their usage seems frivolous in comparison to plain old object-oriented
> techniques.

    Most of the examples given here are kind of silly, but closures have
real uses.  I used one today in Javascript because I was writing an
AJAX application, and I was using an API, the standard XMLHttpRequestObject,
which required a callback function with no arguments.  A closure allowed
the code to pass relevant information with the callback function, which
would be called when a request to the server completed.  A global
variable wouldn't have worked, because multiple instances of the object
making the callback are possible.

    It's a useful tool, but not one you need frequently.  Don't get
carried away.

				John Nagle
				Animats



More information about the Python-list mailing list