gpt4 book ai didi

python - 为什么 __builtins__ 既是模块又是字典

转载 作者:太空狗 更新时间:2023-10-29 17:18:04 24 4
gpt4 key购买 nike

我正在使用内置模块插入一些实例,因此可以全局访问它们以进行调试。 __builtins__ 模块的问题是它是主脚本中的一个模块并且是模块中的一个字典,但是由于我的脚本取决于情况可以是主脚本或模块,我必须这样做这个:

if isinstance(__builtins__, dict):
__builtins__['g_frame'] = 'xxx'
else:
setattr(__builtins__, 'g_frame', 'xxx')

是否有比这更短的解决方法?更重要的是,为什么 __builtins__ 会这样?

这是一个脚本来查看这个。创建一个模块 a.py:

#module-a
import b
print 'a-builtin:',type(__builtins__)

创建模块b.py:

#module-b
print 'b-builtin:',type(__builtins__)

现在运行 python a.py:

$ python a.py 
b-builtin: <type 'dict'>
a-builtin: <type 'module'>

最佳答案

我认为您需要 __builtin__ 模块(注意单数)。

查看文档:

27.3. __builtin__ — Built-in objects

CPython implementation detail: Most modules have the name __builtins__ (note the 's') made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules’s [sic] __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

关于python - 为什么 __builtins__ 既是模块又是字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com