Hi Brian, why not take it the next step and
for key in metadata_dict: if data.startswith(key): exec('''self.%s = """%s"""''' %(metadata_dict[key], data[len(key):])) # triple quotes as there may be quotes in metadata # values break
self.foo = {}
for key in metadata_dict.keys(): #? I got confused, so I guessed. if data.startswith(key): self.foo[metadata_dict[key]]=data[len(key):]
And then instead of self.x (if metadata_dict[key] = x] You just call self.foo['x']
A bit more obfuscated, but it would seem to remove the exec, although I'm not sure how else it impacts your class.
<SNIP related Pythoncard example>
So yeah, hope that helps a wee bit.
Regards,
Liam Clarke
and
Rich Krauter said unto the world upon 2005-02-15 18:09:
> Brian, > > You could use setattr(self,metadata_dict[key],data[len(key):]). > > Rich
Hi Liam, Rich, and all,
thanks for the replies. (And for heroically working through the long question -- if there is a tutee verbosity award, I think its mine ;-)
Rich: thanks. setattr, yeah, that's the ticket!
Liam: The reason I didn't want to take it this way is: "Flat is better than nested" :-)
The code I am working on is an improved (I hope ;-) ) and expanded class-based version of some more primitive code I had done purely procedurally. There, I had a dictionary approach for storing the metadata (akin to the self.foo dictionary you suggested above). One of the benefits of going OOP, in my opinion, is that instead of using dictionary access syntax, you can just say things like self.document_type. It might be little more than sugar[*], but I've a sweet tooth, and I'd want to avoid going back to the dictionary syntax if I could.
Though, absent the setattr way that Rich pointed to, I must admit the exec in my originally posted version would have me dithering whether to opt for sugar or safety. Thankfully, it's all moot.
[*] In that, if I've understood correctly, class namespaces are just fancily packaged dictionaries.
Thanks to all,
Brian vdB
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor