[google-appengine] A safer way to do dynamic property assignment?

2010-04-07 Thread J
I need to assign a value to a Model property but its name is not known
until runtime. For illustrative purposes, say

class Story(db.Model):
title = db.StringProperty()
body = db.TextProperty()

s = Story(title=The Three Little Pigs)

Since I wanted to decide on the property name at runtime, I wrote:
cmd = 's.%s = %s' % ('body', 'Once upon a time...')
exec(cmd)

I shouldn't have to use exec. There has to be a better way of
assigning values to properties.

Any suggestions?

-- 
You received this message because you are subscribed to the Google Groups 
Google App Engine group.
To post to this group, send email to google-appeng...@googlegroups.com.
To unsubscribe from this group, send email to 
google-appengine+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/google-appengine?hl=en.



Re: [google-appengine] A safer way to do dynamic property assignment?

2010-04-07 Thread Nick Johnson (Google)
Hi J,

You can use getattr and setattr for dynamic property access:

s = Story()
setattr(s, 'title', 'The three little pigs')
getattr(s, 'title') # Returns 'The three little pigs'

On Wed, Apr 7, 2010 at 3:31 PM, J j.si...@earlystageit.com wrote:

 I need to assign a value to a Model property but its name is not known
 until runtime. For illustrative purposes, say

 class Story(db.Model):
title = db.StringProperty()
body = db.TextProperty()

 s = Story(title=The Three Little Pigs)

 Since I wanted to decide on the property name at runtime, I wrote:
 cmd = 's.%s = %s' % ('body', 'Once upon a time...')
 exec(cmd)

 I shouldn't have to use exec. There has to be a better way of
 assigning values to properties.

 Any suggestions?

 --
 You received this message because you are subscribed to the Google Groups
 Google App Engine group.
 To post to this group, send email to google-appeng...@googlegroups.com.
 To unsubscribe from this group, send email to
 google-appengine+unsubscr...@googlegroups.comgoogle-appengine%2bunsubscr...@googlegroups.com
 .
 For more options, visit this group at
 http://groups.google.com/group/google-appengine?hl=en.




-- 
Nick Johnson, Developer Programs Engineer, App Engine Google Ireland Ltd. ::
Registered in Dublin, Ireland, Registration Number: 368047
Google Ireland Ltd. :: Registered in Dublin, Ireland, Registration Number:
368047

-- 
You received this message because you are subscribed to the Google Groups 
Google App Engine group.
To post to this group, send email to google-appeng...@googlegroups.com.
To unsubscribe from this group, send email to 
google-appengine+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/google-appengine?hl=en.