title: How to set a Python object's field/member by name
body: <p>I'm doing a simple object marshalling thing that goes between a simple RESTful API to a peewee-managed data store.  However, this pattern keeps on coming up (<code>form</code> being the output of <code>cgi.FieldStorage()</code>):</p>
  
  <pre><code>if form.getfirst('From'): msg.msg_from=form.getfirst('From')
  if form.getfirst('To'): msg.msg_to=form.getfirst('To')
  if form.getfirst('Body'): msg.msg_body=form.getfirst('Body')
  </code></pre>
  
  <p>This is, of course, crufty and hard to maintain. What I'd much rather do is have something like this:</p>
  
  <pre><code>keyMapping = { 'From': 'msg_from',
                 'To': 'msg_to',
                 'Body': 'msg_body' }
  for k, v in keyMapping:
      if form.getfirst(k): msg.SET_FIELD_VALUE(v, form.getfirst(k))
  </code></pre>
  
  <p>Obviously it's the SET_FIELD_VALUE that I'm unable to find.  I know how I can do it using <code>eval</code> but I'd rather avoid that, obviously, and I realize that the actual pattern might actually involve some form of field reference or reflection API or the like instead, but I'm unable to find anything about how one would do that either.</p>