python - 是否可以从 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?
解决方案
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
据我所知,没有办法提取原始字典,或者在不先复制的情况下添加新的键/值对。
推荐阅读
- python - 查找所有不包含特定字符串的组合
- reactjs - 用于 AEM 6.1 和 6.2 版本的 AEM + React 集成
- css - 带系统网格的布局
- r - 根据第一个矩阵的行上的条件在 R 中形成一个新矩阵
- javascript - 在一系列时刻中查找 moment.js 对象?
- react-native - 带有两个按钮的平面列表单项
- sql - SQL:用于两级聚合的 INNER JOIN
- python - 为什么不能在 __init__ 中调用对象属性?
- javascript - 如何在 react-navigation 5 中设置背景颜色
- ios - 如何使用 Swift 在 iOS 中将音频 mp3 文件转换为原始音频类型?