I found some unexpected behavior when debugging my application. Does anyone know why I get the results described below?
from google.appengine.ext import ndb
class Person(ndb.Model):
name = ndb.StringProperty()
shared = ndb.BooleanProperty(default=False)
class Department(ndb.Model):
name = ndb.StringProperty()
persons = ndb.KeyProperty(kind=Person, repeated=True)
@property
def all_department_resources(self):
emp_list = self.persons
for p in Person.query().filter(Person.shared == True):
emp_list.append(p.key)
return emp_list
p1 = Person(name='Jane').put()
p2 = Person(name='Siri').put()
p3 = Person(name='Joe', shared=True).put()
Department(name='Finance',persons=[p1,p2]).put()
print '\n*First run*'
for d in Department.query():
print '>>' + d.name
for p in d.all_department_resources:
print p.get().name
print '\n*Second run:*'
for d in Department.query():
print '>>' + d.name
for p in d.all_department_resources:
print p.get().name
Output:
*First run*
>>Finance
Jane
Siri
Joe
*Second run:*
>>Finance
Jane
Siri
Joe
Joe
My question is simple: Where did the second Joe come from?
In
all_department_resourcesyou add Joe to theself.personslist. And on the second call you add it again. You can confirm this behavior by executing your text block a third time and find three Joes….Why?
does not make a copy of the list, but references it. Everything you do to
emp_listhappens inself.personstoo.What can I do about it?
Either make a copy with
Or you can just add the Query to the return statement: