A problem in Python's implementation of closuresPython's implementation of closures for inner functions has a well known problem: you can't mutate the binding of captured outer variables. In other words, the following code does not work:
There is nothing in the semantics of Python that require this result.
Unlike the case of writing to a global variable in a function, what the
I could make excuses for CPython, but the problem is pretty much
there deliberately; while there is a special bytecode instruction
( The careful phrasing I have had to use in the first paragraph shows the
way around this problem: while you can't change the binding of captured
outer variables in a closure, you can mutate their value directly if the
type of their value allows this. The classical way to do this is to make
the desired variables into arrays, and then mutate the array contents.
So we would write
This version does what we want it to, at the expense of a certain amount of ugliness. (Credit where credit is due department: I think I first saw the array trick in the sample WSGI server code in its specification.) (2 comments.)
|
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 |