Two curious errors when function globals are manipulated

eryk sun eryksun at gmail.com
Tue Jul 5 12:33:36 EDT 2016


On Tue, Jul 5, 2016 at 4:12 PM, Random832 <random832 at fastmail.com> wrote:
> So any special logic in your own __setitem__, which may have
> included e.g. copying it to an alternate place, changing the key or
> value, or simply refusing to add the item to the dictionary at all, will
> be ignored, and your object may end up in an inconsistent state.

In this case, here's the value added by STORE_NAME using
PyObject_SetItem, which calls __setitem__:

    >>> sorted(m)
    ['y']

Here are the values added by STORE_GLOBAL using PyDict_SetItem, which
doesn't call __setitem__:

    >>> sorted(dict(m))
    ['__builtins__', 'x']

ChainMap implements the following __setitem__:

    def __setitem__(self, key, value):
        self.maps[0][key] = value

The item is never actually added to `self` (the dict instance). Then
for __getitem__, we're again only seeing the items from `self.maps`
instead of from `self`:

    def __getitem__(self, key):
        for mapping in self.maps:
            try:
                return mapping[key]
            except KeyError:
                pass
        return self.__missing__(key)



More information about the Python-list mailing list