Why can't I access builtins if I use a custom dict as a function's globals?

烂漫一生 提交于 2019-12-05 06:50:54

Not a complete answer, but what seems to be happening is that CPython ignores the custom __getitem__ when it accesses the builtins. It seems to treat MyDict like a normal (not subclassed) dict. If the '__builtins__' key is actually present in the dict, then everything works correctly:

class MyDict(dict):
    def __getitem__(self, name):
        return globals()[name]


import types

globs = MyDict()
globs['__builtins__'] = __builtins__

func = lambda: bytearray
func_copy = types.FunctionType(func.__code__,
                              globs,
                              func.__name__,
                              func.__defaults__,
                              func.__closure__)

print(func_copy())
# output: <class 'bytearray'>

The question remains why this only happens with FunctionType, and not with eval and exec.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!