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.)


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) »

These are my WanderingThoughts
(About the blog)

Full index of entries
Recent comments

This is part of CSpace, and is written by ChrisSiebenmann.
Twitter: @thatcks

* * *

Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web

This is a DWiki.
GettingAround
(Help)

Search:

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

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