Implicit dict to ndb.Model conversion in Python Google App Engine

269 views Asked by At

I ran into this feature (?) where dictionaries are implicitly converted to ndb.Model objects

I have following ndb.Model class

class DateOfBirth(ndb.Model)
  day = ndb.IntegerProperty()
  month = ndb.IntegerProperty()
  year = ndb.IntegerProperty()

class User(ndb.Model):
   dob = ndb.StructuredProperty(DateofBirth)

And at one place when I accidentally passed in a dict

user.dob = {"day": 12, "month": 10, "year": 1983}

It didn't complain and looks like it worked.

Is this expected, or am I expected to run into issues later (as this behavior is not documented and expected to break anytime)

1

There are 1 answers

1
Greg On BEST ANSWER

It was a surprise to me, and I've been using NDB for a long time! But from the code, it seems it was intended: https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/caac0c3e7dd4d9b2c6b32dfc5d59386dd02e6b57/ndb/model.py#L2354

It would only be a small change to your code to not to have to rely on the behaviour though:

user.dob = DateOfBirth(**{"day": 12, "month": 10, "year": 1983})