Jython中自定义字典/映射的奇怪解包

2024-04-20 06:48:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Jython中遇到了一个奇怪的字典/映射解包行为。最初,在SQLAlchemy的上下文中,但我设法将其缩小到以下最小的示例:

import collections

class CustomMapping(collections.MutableMapping):
    def __init__(self):
        self.storage = {}

    def __setitem__(self, key, value):
        self.storage[key] = value

    def __getitem__(self, key):
        print('Accessed CustomMapping instance for key %s' % key)
        return self.storage[key]

    def __delitem__(self, key):
        del self.storage[key]

    def __len__(self):
        return len(self.storage)

    def __iter__(self):
        for key in self.storage:
            yield key

    def __str__(self):
        return str(self.storage)

现在我运行这个测试代码:

print(dict(
    name='test', _some_stuff='abc', more='def', **CustomMapping())
)

在Python2.7中,我得到了我所期望的:

{'more': 'def', '_some_stuff': 'abc', 'name': 'test'}

但在Jython 2.7.0中,我得到了:

Accessed CustomMapping instance for key name

Accessed CustomMapping instance for key _some_stuff

Accessed CustomMapping instance for key more

{'more': 'def', '_some_stuff': 'abc', 'name': 'test'}

在调试器中设置断点还可以确认,在解包期间,__getitem__实例的CustomMapping方法对于外部字典中的每个键都被访问。这是非常令人费解的,只发生在Jython,看起来像一个虫子对我来说。虽然上面的示例使用dict作为外部函数,但任何其他函数都可以。你知道吗

我希望有人能对这种行为有所了解。在我的真实环境中,这在我的SQLAlchemy驱动的应用程序中造成了一些恶劣的行为。非常感谢您的帮助。你知道吗


Tags: instancekeynametestselfforreturndef