On Thu, Jun 12, 2014 at 12:18 PM, Robert Lehmann <m...@robertlehmann.de> wrote:
> Hi all,
>
> I have noticed there is a slight asymmetry in the way the interpreter
> (v3.3.5, reproduced also in v3.5.x) loads and stores globals.  While loading
> globals from a custom mapping triggers __getitem__ just fine, writing seems
> to silently ignore __setitem__.
>
> class Namespace(dict):
>     def __getitem__(self, key):
>         print("getitem", key)
>     def __setitem__(self, key, value):
>         print("setitem", key, value)
>
> def fun():
>     global x, y
>     x  # should call globals.__getitem__
>     y = 1  # should call globals.__setitem__
>
> exec(fun.__code__, Namespace())
> # => getitem x
>
> I would have expected "setitem y 1" to show up as well, but to no avail.  Am
> I doing something wrong?  Is this on purpose?

Seems like a bug to me.  I note that the STORE_NAME opcode does call
__setitem__:

>>> code = compile('x = 1', '', 'exec')
>>> dis.dis(code)
  1           0 LOAD_CONST               0 (1)
              3 STORE_NAME               0 (x)
              6 LOAD_CONST               1 (None)
              9 RETURN_VALUE
>>> exec(code, Namespace())
setitem x 1

But STORE_GLOBAL does not:

>>> code = compile('global x; x = 1', '', 'exec')
>>> dis.dis(code)
  1           0 LOAD_CONST               0 (1)
              3 STORE_GLOBAL             0 (x)
              6 LOAD_CONST               1 (None)
              9 RETURN_VALUE
>>> exec(code, Namespace())
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to