检查变量是否为字典 - 使用 'is' 还是 ==
总结:我有一个叫做 'parent'
的变量,它是一个字典(dictionary),在python中使用。现在我想检查一下它是不是一个 dict
对象。但是,当我用 "type(parent) is dict"
来检查时,结果却是 'False'
。
注意:在我的python脚本中加载了以下库:
from google.appengine.ext import ndb
为什么会这样呢?我一开始怀疑是因为这个变量 'parent'
是通过 json
库的 'loads'
方法创建的。
parent = json.loads(self.request.body)
但是,即使我这样创建 parent
,
parent = {}
我得到的结果还是和下面观察到的一样:
print type(parent)
>> <type 'dict'>
print type(parent) is dict
>> False
print type({}) is type(parent)
>> True
print type(parent) == dict
>> False
print type({}) == type(parent)
>> True
这到底是怎么回事?是python版本的问题吗?还是说这和我加载的谷歌应用引擎库有关?当我在一个没有加载任何库的普通终端中执行以下命令(Python 2.7.5),我得到的结果是我预期的:
Python 2.7.5 (default, Sep 12 2013, 21:33:34)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
>>> parent = {}
>>> print type(parent)
<type 'dict'>
>>> print type(parent) is dict
True
>>> print type({}) is dict
True
>>> print type({}) is type(parent)
True
>>> print type({}) == type(parent)
True
提前感谢任何指导!
1 个回答
6
最有可能发生的情况是,GAE在后台使用了一种字典的子类。
在Python中,检查一个对象是否属于某种类型的标准方法是使用isinstance()
这个内置函数:
>>> parent = {}
>>> isinstance(parent, dict)
True
... 这个方法适用于该类型本身的实例,以及它的子类。