Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround to return a list from a ComputedProperty function in NDB

I am converting my app to use NDB. I used to have something like this before:

@db.ComputedProperty
    def someComputedProperty(self, indexed=False):
      if not self.someCondition:
          return []
      src = self.someReferenceProperty
      list =  src.list1 + src.list2 + src.list3 + src.list4 \
              + [src.str1, src.str2]
      return map(lambda x:'' if not x else x.lower(), list) 

As you can see, my method of generating the list is a bit complicated, I prefer to keep it this way. But when I started converting to NDB, I just replaced @db.ComputedProperty by @model.ComputedProperty but then I got this error:

NotImplementedError: Property someComputedProperty does not support <type 'list'> types.

I could see in model.py in ext.ndb that ComputedProperty inherits from GenericProperty where in the _db_set_value there are several if/else statements that handle value according to its type, except that there's no handling for lists

Currently it goes through the first condition and gives out that error when I return an empty list.

Is there a way to work around this and avoid the error?

like image 386
Mohamed Khamis Avatar asked Dec 04 '22 18:12

Mohamed Khamis


1 Answers

You need to set the repeated=True flag for your computed property in NDB. I don't think you can use the cute "@db.ComputedProperty" notation, you'll have to say:

def _computeValue(self):
    ...same as before...
someComputedProperty = ComputedProperty(_computeValue, repeated=True, indexed=False)
like image 87
Guido van Rossum Avatar answered Jan 21 '23 10:01

Guido van Rossum