1

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)

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
user462455
  • 12,838
  • 18
  • 65
  • 96

1 Answers1

3

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})
Greg
  • 10,350
  • 1
  • 26
  • 35
  • 1
    This is intended. In fact, unpacking a dict (or calling populate with the dict) is the easy way to go on creating entities. – janscas Nov 21 '16 at 09:51