[Tutor] Quoting trouble
Marilyn Davis
marilyn at deliberate.com
Sat Jan 21 00:45:18 CET 2006
On Fri, 20 Jan 2006, Python wrote:
> 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)
Very nice indeed!
>
>
> Hope this helps. The ease with which Python allows you to attach names
> to values is one of the great features of the language.
Yes. Thank you so much. I'll fix it and I'm glad to have it in my
bag of tricks.
Marilyn
>
>
--
More information about the Tutor
mailing list