[Tutor] Quoting trouble
Python
python at venix.com
Sat Jan 21 00:13:51 CET 2006
On Fri, 2006-01-20 at 13:50 -0800, Marilyn Davis wrote:
> for each in significant_headers.keys():
> this = '''self.h_%s = "%s"''' % \
> (each[:-2].lower().replace('-','_'),
> repr(significant_headers[each]))
> exec(this)
So you are using exec to process an assignment statement. The setattr
builtin function will do what you want.
http://docs.python.org/lib/built-in-funcs.html#l2h-64
so your code could wind up looking something like:
setattr( self,
'h_' + each[:-2].lower().replace('-','_'),
significant_headers[each]
)
Looking at that code, you can pull the key and value from
significant_headers in the for statement. That is:
for key,val in significant_headers.items():
setattr( self,
'h_' + key[:-2].lower().replace('-','_'),
val
)
Now the line that actually determines the attribute name looks pretty
ugly. I would recommend writing a function to replace that operation
with an understandable function name (perhaps key2name). That would
result in:
setattr(self, key2name(key), val)
Hope this helps. The ease with which Python allows you to attach names
to values is one of the great features of the language.
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list