On 11/24/07, Neil Toronto firstname.lastname@example.org wrote:
[I'm summarizing and paraphrasing]
If a name isn't in globals, python looks in globals['__builtins__']['name'] Unfortunately, it may use a stale cached value for globals['__builtins__'] ...
Well, keeping in mind this strange behavior and the length of time it's gone on, here's my recommendation:
Kill __builtins__. Take it out of the module dict. Let LOAD_GLOBAL look in "builtins" (currently "__builtin__") for names after it checks globals. If modules want to hack at builtins, they can import it. But they hack it globally or not at all.
As Greg pointed out, this isn't so good for sandboxes.
But as long as you're changing dicts to be better namespaces, why not go a step farther? Instead of using a magic key name (some spelling variant of builtin), make the fallback part of the dict itself. For example:
Use a defaultdict and set the __missing__ method to the builtin's __getitem__.
Then neither python nor the frame need to worry about tracking the builtin namespace, but the fallback can be reset (even on a per-function basis) by simply replacing the fallback method.