首页 > 解决方案 > 是否可以从 MappingProxyType 实例中提取包装的映射?

问题描述

是否有任何跨平台方法可以通过拥有该映射的MappingProxyType实例来获取对该映射对象的引用?

>>> class A: pass
>>> A.__dict__ # is there a way to get the wrapped dict of this proxy?
mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})

或者

>>> import types
>>> m = {1: 2}
>>> mp = types.MappingProxyType(m) # how to extract m from mp?

标签: pythonpython-3.xpython-internals

解决方案


MappingProxyType就像一个dict方法__setattr__总是会抛出错误。按照设计,您不能添加任何新的键/值对。但是,您可以在普通字典中获取其内容的浅表副本

假设您有一个映射代理...

import types

# Given a normal dictionary...
dictionary = {
  "foo": 10,
  "bar": 20,
}

# That has been wrapped in a mapping proxy...
proxy = types.MappingProxyType(dictionary)

# That cannot accept new key/value pairs...
proxy["baz"] = 30 # Throws TypeError: 'mappingproxy' object does not support item assignment

您可以像这样创建其内部字典的浅表副本:

dictionary_copy = proxy.copy()

print(type(dictionary_copy))         # Prints "<class 'dict'>"
print(dictionary_copy is dictionary) # Prints "False" because it's a copy

dictionary_copy["baz"] = 30          # Doesn't throw any errors

据我所知,没有办法提取原始字典,或者在不先复制的情况下添加新的键/值对。


推荐阅读