python - 关闭 __class__

标签 python python-3.x closures python-internals

我最近正在单步调试 CPython 源代码,特别是查看 symbol table entry编译期间的一个类。

我遇到了 typedef struct _symtable_entry 的以下条目结构:

[-- other entries --]
unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
                                         closure over __class__
                                         should be created */
[-- other entries --]

我真的看不懂,也找不到实际设置ste_needs_class_closure == 1的python代码示例.在其他失败的尝试中,我尝试了以下方法:

class foo:
    y = 30
    def __init__(self):
        self.x = 50
    def foobar(self):
        def barfoo():
            print(self.x)
            print(y)
        return barfoo

但是即使它执行了,ste_needs_class_closure 的值执行期间是0而不是 1正如我所希望的那样。

实际改变这个值的函数是 drop_class_free 这没有多大帮助。不幸的是,它也没有任何赞美它的评论。

实际用在 analyze_block 评论如下:

/* Check if any local variables must be converted to cell variables */

我可以将其理解为一个概念,但找不到它发生的例子。

我试过搜索 the changelog for Python 3.4 , 该成员首次出现但未找到对其的引用的版本。

那么,谁能解释一下对__class__ 的闭包 是什么意思,即类的局部变量何时转换为单元变量?理想情况下,一个在执行期间实际使此行为可见的示例会很棒。

最佳答案

Github’s blame view for that line of code向我们展示它是在 this commit 中添加的, 其中引用 Issue #12370 : 防止类体干扰 __class__ 闭包。

根据错误报告,此尝试修复的问题类型的示例是:

In Python 3 the following code prints False because the use of super() has caused the __class__ descriptor to be omitted from the class namespace. Remove the use of super and it prints True.

class X(object):
    def __init__(self):
        super().__init__()

    @property
    def __class__(self):
        return int

print (isinstance(X(), int))

(请注意,此代码使用了 new super() 。)

关于补丁的功能,同样来自错误报告:

The patch basically causes the following class statement:

class C(A, B, metaclass=meta):
    def f(self):
        return __class__

To be compiled approximately like this:

def _outer_C(*__args__, **__kw__):
    class _inner_C(*__args__, **__kw__):
        def f(self):
            return __class__
    __class__ = _inner_C
    return _inner_C 
C = _outer_C(A, B, metaclass=meta)

…尽管后来的一些讨论表明 __args____kw__ 的处理可能在最终补丁中发生了变化。

关于python - 关闭 __class__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563179/

相关文章:

python - 用 galsim 插值 PSF 参数

python - 为什么这个 Python 函数不返回 future ?

python-3.x - 在 Linux Mint 上安装 Python

javascript - 解决js中getter丑陋的语法

Python 正则表达式创建

python - 将所有子图的 yaxis 设置为相同的范围 - Matplotlib

python-3.x - 多线程python3服务器

python - 强制从 URL 下载图像的最长时间

javascript - 使用 Object.DefineProperty 并访问私有(private)范围内的变量

javascript - 对返回带有许多粗箭头的多个函数的 javascript 函数感到困惑