checking whether variable is dictionary in python - use 'is' or ==
Question: Summary: I have a variable called `'parent'` that is a dictionary in python. I
want to check if it is a `dict` object. However, using `"type(parent) is
dict"` gives me `'False'`.

NOTE: I have the following library loaded in my python script:

    
    
    from google.appengine.ext import ndb
    

Why is this happening? I suspected at first it is because this variable
`'parent'` is created using the `json` library's `'loads'` method.

    
    
    parent = json.loads(self.request.body)
    

However, even when I create parent like so,

    
    
    parent = {}
    

I get the the same results as observed below:

    
    
            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
    

What's going on here? Is this a python version issue? Or does this have to do
with the fact I've loaded google's app engine library? When I execute the
following commands in a normal terminal, with no libraries loaded (Python
2.7.5), I get the following results, which are what I expect:

    
    
    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
    

Thanks in advance for any guidance!


Answer: What's most likely happening is that GAE is using some subclass of `dict`
behind the scenes.

The idiomatic way to check whether an object is an instance of a type in
python is the
[`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance)
built-in function:

    
    
    >>> parent = {}
    >>> isinstance(parent, dict)
    True
    

... which works for instances of the type itself, and of subclasses.

