Python unittest不将UserDict视为dict

Python unittest不将UserDict视为dict,python,python-unittest,Python,Python Unittest,我得到 我是否应该使用内置的dict作为基类,而不是UserDict?问题在于首先检查两个参数是否都是dict实例: AssertionError: Second argument is not a dictionary 而且,UserDict不是dict的实例: def assertDictEqual(self, d1, d2, msg=None): self.assertIsInstance(d1, dict, 'First argument is not a dictionary

我得到

我是否应该使用内置的
dict
作为基类,而不是
UserDict

问题在于首先检查两个参数是否都是
dict
实例:

AssertionError: Second argument is not a dictionary
而且,
UserDict
不是
dict
的实例:

def assertDictEqual(self, d1, d2, msg=None):
    self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
    self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
    ...
不要直接使用
UserDict
类,而是使用
data
属性,该属性包含一个真正的字典:

>>> m = UserDict(x=42)
>>> m
{'x': 42}
>>> isinstance(m, dict)
False

或者,正如其他人已经建议的那样,只使用常规字典。

问题在于,
UserDict
实际上不是一个
dict
对象,因为它是在很久以前创建的,当时您无法继承内置的
dict
类型。根据报告:

[UserDict]已被直接从
dict
生成子类的能力所取代

所以我可能只是继承了dict的
dict
,然后就不用它了;我看不到
UserDict
在该选项上提供的任何功能


请注意,我个人对
UserDict
*也有异议,因为模块名很烦人



*直到八分钟前我才知道它的存在。

来自Python unittess源代码

self.assertDictEqual({'x': 42}, m.data)
这两个参数必须是dict的实例

不幸的是,UserDict实例不是dict的实例

def assertDictEqual(self, d1, d2, msg=None):
   self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
   self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
正如doc所说,您可以使用m.data返回一个真正的dict

ITerablueserdict.data

assert isinstance(m, dict) # this is False

可能什么是
UserDict
?它从哪里来(和)?@HenryKeiter看,你总是可以将
m
转换为dict:
dict(m)
或使用
m.data
而不是
m
@alecxe ew。。。我从来不知道。我猜ASKER应该测试<代码>数据> /代码>首先,考虑你是否真的需要你自己的DICT类,这是非常罕见的。其次,只是从
dict
继承,我不知道为什么要从UserDict继承。(这在非常旧的python版本中是必需的)。
assert isinstance(m, dict) # this is False
A real dictionary used to store the contents of the UserDict class.