Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #73234 > unrolled thread
| Started by | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| First post | 2014-06-12 12:48 -0600 |
| Last post | 2014-06-12 12:48 -0600 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Asymmetry in globals __getitem__/__setitem__ Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-12 12:48 -0600
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2014-06-12 12:48 -0600 |
| Subject | Re: Asymmetry in globals __getitem__/__setitem__ |
| Message-ID | <mailman.11040.1402598976.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web