A frame object's f_locals isn't always the locals

August 26, 2009

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:

From 209.124.161.130 at 2009-08-26 10:39:29:

Perhaps it would be better if f_locals was always read only.

That would definitely be less confusing. I also feel like I should write a doc patch to add some detail to the inspect module's docs.

And your quote about modifying f_locals only being useful for "dubious hacks" in the page you link is extremely accurate :)

From 209.124.161.130 at 2009-08-26 10:40:26:

Oh, and I should add, the last two comments have been written by Bill Mill.

-Bill Mill

Written on 26 August 2009.
« The problem with the CFQ IO scheduler and our iSCSI targets
What packages SystemTap requires on Ubuntu 8.04 (and others) »

Page tools: View Source, View Normal.
Search:
Login: Password:

Last modified: Wed Aug 26 00:29:25 2009
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.