Steven said:
I remember hearing an explanation of why locals() is not writable that
had to do with something about efficiency and the call stack (or
something like that)...
IIRC, the function local namespace (in CPython) is kept internally as a
static array, rather than as a dictionary, which dramatically speeds
(function-local) name lookups. However, this also means that all local
names must be determinable at function-definition time. In contrast,
the global namespace is a true Python dictionary. Where globals()
returns a reference to that dictionary, locals() (when locals() is not
globals()) constructs a separate dictionary from the static array
containing the local namespace. In effect, globals() gives a reference
while locals() gives a copy, with standard Python reference/copy
semantics applying.
(Note also that functions which use exec cannot use the static namespace
optimization, and thus tend to be *much* slower than normal functions
(in addition to being a huge security problem). I don't know, however,
whether locals() can update the local namespace in such un-optimized
functions. Whether it actually does so or not, relying on such
special-case behavior would be extremely foolish to do...)
Of course, I'm just going off of what I remember having been said
elsewhere on c.l.p., and I wouldn't recommend anyone betting their life
savings on the reliability of my memory...
Jeff Shannon
Technician/Programmer
Credit International