|
2011-10-07 Python's philosophy of what closures close overA commentator on my last entry on closures said:
I think the real answer is 'because how Python does it is how languages usually do it'. Let me elaborate on that. When you add closures to a language, you are faced with a design choice (or a philosophical question). Consider the following code:
Here (Given a suitable choice of when a closure is created, I don't think that there's a right or a wrong answer here, just different ones.) Like most languages with closures, Python has picked the first choice; free variables are bound to variables, not to values. There are pragmatic reasons for choosing this, including that it is most compatible with how global variables are treated in ordinary functions, but ultimately it is a choice. I don't think there's anything in Python's other semantics that require it. Making this choice creates a second one, which is what a variable's
'lifetime' is; when does
In this code the scope of This example probably seems artificial. Now consider the same question recast as:
The scope of (If nothing else, this makes the interpreter's implementation simpler.) PS: with very careful use of scopes you can make what I'm calling
variable lifetime here into scope lifetime, even with each loop body
getting its own version of Sidebar: a pragmatic problem with 'bind to value' in PythonThe problem is that This means that if closures bound to values instead of variables you might well have to move inner function definitions down in your function so that they were intermixed with actual code, because you would need to insure that they were only defined (and the closure created) after all of the variables they needed had been set up. And (as I saw mentioned somewhere) you couldn't have mutually recursive closures without awkward hacks. (2 comments.)
python/WhatClosuresClose written at 02:42:01; Add Comment
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |