检查变量是否是python中的字典 - 使用'is'或==

jmt*_*ung 2 python google-app-engine json

简介:我有一个名为'parent'python中的字典的变量.我想检查它是否是一个dict对象.但是,使用"type(parent) is dict"给了我'False'.

注意:我的python脚本中加载了以下库:

from google.appengine.ext import ndb
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我首先怀疑是因为这个变量'parent'是使用json库的'loads'方法创建的.

parent = json.loads(self.request.body)
Run Code Online (Sandbox Code Playgroud)

但是,即使我这样创建父母,

parent = {}
Run Code Online (Sandbox Code Playgroud)

我得到与下面观察到的相同的结果:

        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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?这是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
Run Code Online (Sandbox Code Playgroud)

在此先感谢任何指导!

Zer*_*eus 6

最可能发生的是GAE正在使用dict幕后的一些子类.

在python中检查对象是否是类型实例的惯用方法是isinstance()内置函数:

>>> parent = {}
>>> isinstance(parent, dict)
True
Run Code Online (Sandbox Code Playgroud)

...适用于类型本身和子类的实例.