This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author douglas-raillard-arm
Recipients douglas-raillard-arm
Date 2021-07-27.14:13:34
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1627395215.45.0.945166676554.issue44749@roundup.psfhosted.org>
In-reply-to
Content
Re-raising the bug reported by Kevin Shweh:
thread: https://bugs.python.org/issue14385
message: https://bugs.python.org/msg337245

Here is a copy for easier reference:

The patch for this issue changed LOAD_GLOBAL to use PyObject_GetItem when globals() is a dict subclass, but LOAD_NAME, STORE_GLOBAL, and DELETE_GLOBAL weren't changed. (LOAD_NAME uses PyObject_GetItem for builtins now, but not for globals.)

This means that global lookup doesn't respect overridden __getitem__ inside a class statement (unless you explicitly declare the name global with a global statement, in which case LOAD_GLOBAL gets used instead of LOAD_NAME).

I don't have a strong opinion on whether STORE_GLOBAL or DELETE_GLOBAL should respect overridden __setitem__ or __delitem__, but the inconsistency between LOAD_GLOBAL and LOAD_NAME seems like a bug that should be fixed.

For reference, in the following code, the first 3 exec calls successfully print 5, and the last exec call fails, due to the LOAD_GLOBAL/LOAD_NAME inconsistency:

class Foo(dict):
    def __getitem__(self, index):
        return 5 if index == 'y' else super().__getitem__(index)
 
exec('print(y)', Foo())
exec('global y; print(y)', Foo())
exec('''
class UsesLOAD_NAME:
    global y
    print(y)''', Foo())
exec('''
class UsesLOAD_NAME:
    print(y)''', Foo())


I encountered the same issue when trying to create a way to "instantiate" modules with some globals replaced by user-defined values to make a dependency-injection system. I therefore want to lookup some names in a separate dict rather than getting the value normally bound in that module (typically by an import statement).
History
Date User Action Args
2021-07-27 14:13:35douglas-raillard-armsetrecipients: + douglas-raillard-arm
2021-07-27 14:13:35douglas-raillard-armsetmessageid: <1627395215.45.0.945166676554.issue44749@roundup.psfhosted.org>
2021-07-27 14:13:35douglas-raillard-armlinkissue44749 messages
2021-07-27 14:13:34douglas-raillard-armcreate