使用 __getitem__ python 3.5 与 python 3.6 就地自定义对象解包不同的行为

In-place custom object unpacking different behavior with __getitem__ python 3.5 vs python 3.6

关于 this question 的后续问题:我 运行 下面关于 python 3.5 和 python 3.6 的代码 - 结果截然不同:

class Container:

    KEYS = ('a', 'b', 'c')

    def __init__(self, a=None, b=None, c=None):
        self.a = a
        self.b = b
        self.c = c

    def keys(self):
        return Container.KEYS

    def __getitem__(self, key):
        if key not in Container.KEYS:
            raise KeyError(key)
        return getattr(self, key)

    def __str__(self):
        # python 3.6
        # return f'{self.__class__.__name__}(a={self.a}, b={self.b}, c={self.c})'
        # python 3.5    
        return ('{self.__class__.__name__}(a={self.a}, b={self.b}, '
                'c={self.c})').format(self=self)

data0 = Container(a=1, b=2, c=3)
print(data0)

data3 = Container(**data0, b=7)
print(data3)

如前一个问题所述,这引发了

TypeError: type object got multiple values for keyword argument 'b'

在 python 上 3.6。但是在 python 3.5 上我得到了异常:

KeyError: 0

此外,如果我不加注 KeyError 而只是在 __getitem__ 中打印出 keyreturn:

def __getitem__(self, key):
    if key not in Container.KEYS:
        # raise KeyError(key)
        print(key)
        return
    return getattr(self, key)

这将打印出 int 序列 0, 1, 2, 3, 4, ...。 (python 3.5)

所以我的问题是:


UPDATE :如 λuser 评论中所述:实施 __iter__ 将更改 python 3.5 上的行为以匹配 python 3.6 做:

def __iter__(self):
    return iter(Container.KEYS)

这实际上是在解包自定义映射对象和创建调用者参数的过程中多个内部操作之间的复杂冲突。因此,如果您想彻底了解根本原因,我建议您查看源代码。但是,这里有一些提示和起点,您可以查看它们以了解更多详细信息。

在内部,当您在调用者级别解包时,字节码 BUILD_MAP_UNPACK_WITH_CALL(count) pops count mappings from the stack, merges them into a single dictionary and pushes the result. In other hand, the stack effect of this opcode with argument oparg is defined as following:

case BUILD_MAP_UNPACK_WITH_CALL:
    return 1 - oparg;

话虽如此,让我们看一下示例的字节码(在 Python-3.5 中)以了解实际情况:

>>> def bar(data0):foo(**data0, b=4)
... 
>>> 
>>> dis.dis(bar)
  1           0 LOAD_GLOBAL              0 (foo)
              3 LOAD_FAST                0 (data0)
              6 LOAD_CONST               1 ('b')
              9 LOAD_CONST               2 (4)
             12 BUILD_MAP                1
             15 BUILD_MAP_UNPACK_WITH_CALL   258
             18 CALL_FUNCTION_KW         0 (0 positional, 0 keyword pair)
             21 POP_TOP
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE
>>> 

如您所见,在偏移量 15 处我们有 BUILD_MAP_UNPACK_WITH_CALL 字节代码负责解包。

现在 returns 0 作为 __getitem__ 方法的 key 参数会发生什么?

每当解释器在解包过程中遇到异常时,在本例中是 KeyError,它会停止继续 push/pop 流程,而不是返回变量的实际值 returns 堆栈效应,这就是为什么键一开始是 0 的原因,如果你每次得到递增的结果时都不处理异常(由于堆栈大小)。

现在,如果您在 Python-3.6 中进行相同的反汇编,您将得到以下结果:

>>> dis.dis(bar)
  1           0 LOAD_GLOBAL              0 (foo)
              2 BUILD_TUPLE              0
              4 LOAD_FAST                0 (data0)
              6 LOAD_CONST               1 ('b')
              8 LOAD_CONST               2 (4)
             10 BUILD_MAP                1
             12 BUILD_MAP_UNPACK_WITH_CALL     2
             14 CALL_FUNCTION_EX         1
             16 POP_TOP
             18 LOAD_CONST               0 (None)
             20 RETURN_VALUE

在创建局部变量 (LOAD_FAST) 之前和在 LOAD_GLOBAL 之后,有一个 BUILD_TUPLE 负责创建元组并从堆栈中消耗计数项。

BUILD_TUPLE(count)

Creates a tuple consuming count items from the stack, and pushes the >resulting tuple onto the stack.

在我看来,这就是为什么您没有收到密钥错误而是收到 TypeError 的原因。因为在创建参数元组的过程中,它遇到了重复的名称,因此,returns TypeError.

是正确的