A frame object's f_locals
isn't always the locals
Python frame objects have a tempting member called f_locals
, which
is described as the 'local namespace seen by this frame' (to quote the
inspect module). This is
slightly misleading, because it is not always what Python programmers
normally think of as 'locals'.
Specifically, if the frame comes from code that is running at the
module level, f_locals
is the 'local namespace' of that code,
that is, it is the module's namespace. In other words, it's the same
as f_globals
, and in fact both of them are live references to the
module's name dictionary.
This is a gotcha because it means that f_locals
has significantly
different behavior between module level code and function level code.
For module level code, you can modify f_locals
and it actually
works; for function level code, modifying f_locals
doesn't do
anything.
(Perhaps it would be better if f_locals
was always read only.
There's plausible ways of making this inexpensive for module level
frames.)
You might now wonder how you tell if a frame belongs to module level
code or function level code. One answer is that you can look at
f_code.co_name
, which will be "<module>"
for module level code.
You can also see if f_locals
and f_globals
are the same thing.
(I suspect that you can play extensive games with eval()
that will
fool some or all of these checks. So don't do that.)
On a side note, the other odd looking frame object member is
f_builtins
. Under most circumstances, this is the same as
__builtins__.__dict__
.
(My attention was drawn to this confusing situation by Multi-Line Lambdas in Python Using the With Statement by Bill Mill.)
Comments on this page:
|
|