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

发布于 2024-07-27 20:15:18 字数 691 浏览 5 评论 0原文

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

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'>

I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the __builtins__ module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this:

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

Is there a workaround, shorter than this? More importantly, why does __builtins__ behave this way?

Here is a script to see this. Create a module a.py:

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

Create a module b.py:

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

Now run python a.py:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌伤ぢ 2024-08-03 20:15:18

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

请参阅文档:

27.3。 __builtin__ — 内置对象

CPython 实现细节: 大多数模块都将名称 __builtins__(注意 's')作为其全局变量的一部分提供。 __builtins__ 的值通常是该模块或该模块的 [sic] __dict__ 属性的值。 由于这是一个实现细节,因此 Python 的替代实现可能不会使用它。

I think you want the __builtin__ module (note the singular).

See the docs:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文