2

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!

Jerry YY Rain
  • 4,134
  • 7
  • 35
  • 52
jmtoung
  • 1,002
  • 1
  • 14
  • 28

1 Answers1

6

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() built-in function:

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

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

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160