Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #73234
| References | <CA+76LTGPSV3dwjygE0Jn_0vXqNoLmYN08JmSyVndrtSM_39VZg@mail.gmail.com> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2014-06-12 12:48 -0600 |
| Subject | Re: Asymmetry in globals __getitem__/__setitem__ |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.11040.1402598976.18130.python-list@python.org> (permalink) |
On Thu, Jun 12, 2014 at 12:18 PM, Robert Lehmann <mail@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())
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Asymmetry in globals __getitem__/__setitem__ Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-12 12:48 -0600
csiph-web