views:

41

answers:

1

If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example:

class MyEntity(db.Expando):  
  x = db.IntegerProperty()  

my_entity = MyEntity(x=1)  
my_entity.y = 2  

But suppose I have the name of the dynamic property in a variable... how can I (1) read and write to it, and (2) check if the Dynamic variable exists in the entity's instance? e.g.

class MyEntity(db.Expando):  
  x = db.IntegerProperty()  

my_entity = MyEntity(x=1)  
# choose a var name:  
var_name = "z"  
# assign a value to the Dynamic variable whose name is in var_name:  
my_entity.property_by_name[var_name] = 2  
# also, check if such a property esists  
if my_entity.property_exists(var_name):  
  # read the value of the Dynamic property whose name is in var_name
  print my_entity.property_by_name[var_name]  

Thanks...

+4  A: 

Yes, you can. You simply have to set the attribute on the entity:

some_name = 'wee'
setattr(my_entity, some_name, 'value')
print getattr(my_entity, some_name)
my_entity.put()

setattr and getattr are built-in functions of Python used to set/get attributes with arbitrary names on an object.

Blixt
Perfect, thanks! I also saw that I can use hasattr to find out if an entity has a dynamic variable or not.
MarcoB