tags:

views:

42

answers:

1
class all_items(dict):
    def __getitem__(self, key):
       return 1

>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    eval("undefined",all_items(),dict())
  File "<string>", line 1, in <module>
NameError: name 'undefined' is not defined

The all_items class of dictionary should return 1 for any value. Using the eval function, I want "undefined" to evaluate to 1, even though it isn't defined. This works when the all_items dictionary is the third argument of the eval statement, but not when it is the second argument. My question is why doesn't the second statment evaluate to 1? (And how could I make it work?) I'm using Python 2.5.

+3  A: 

The second argument must be a dictionary. Implementing the mapping protocol isn't enough.

Ignacio Vazquez-Abrams
Is a subclass of dict not a dictionary?
dp_
Well... that depends on how you define "is".
Ignacio Vazquez-Abrams
And define "must" while you're at it. There is no type error. If it is true that it fails because it is not a dictionary, how does it fail?
dp_
http://docs.python.org/library/functions.html#globals describes the second argument in a little more detail.
Scott
After looking through the Python source code, it's because the code to load from the globals uses `PyDict_GetItem()` (or rather inlined copies of such) instead of `PyMapping_GetItemString()`, therefore only the raw dictionary is used. So the answer then is that it must be exactly a dict.
Ignacio Vazquez-Abrams
Thanks, but that describes the globals function, not the second argument of eval.
dp_
Thanks Ignacio, that answers the question!
dp_