[docs] [issue15099] exec of function doesn't call __getitem__ or __missing__ on undefined global

John Firestone report at bugs.python.org
Mon Jun 18 19:45:03 CEST 2012


John Firestone <johnf at freenet.de> added the comment:

Thank you all for the quick and interesting responses!

Here is another example, this time showing a simple
    s
sometimes behaves like
    globals()['s']
and sometimes doesn't.

class Dict(dict):
    def __getitem__(self, key):
        if key == 's':
            return 'got s'
        return dict.__getitem__(self, key)

dct = Dict()
dct['the_dict'] = dct
print 0, id(dct)

source = """if 1:
    print '1', id(globals()), globals() is the_dict
    print ' ', globals()['s']
    print ' ', s
    def f():
        print '2', id(globals()), globals() is the_dict
        print ' ', globals()['s']
        print ' ', s
        print '3'
    f()"""

exec(source, dct)


Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:32:06) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
>>> import curiosity2
0 2459928
1 2459928 True
  got s
  got s
2 2459928 True
  got s
 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "curiosity2.py", line 22, in <module>
    exec(source, dct)
  File "<string>", line 10, in <module>
  File "<string>", line 8, in f
NameError: global name 's' is not defined
>>>

----------
Added file: http://bugs.python.org/file26044/curiosity2.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15099>
_______________________________________


More information about the docs mailing list