[Tutor] Exec(uting) Code in a Dictionary?
Kent Johnson
kent37 at tds.net
Sat Feb 7 22:42:05 CET 2009
On Sat, Feb 7, 2009 at 4:21 PM, Wayne Watson
<sierra_mtnview at sbcglobal.net> wrote:
> Here's more detail. What I was hoping for was something like:
>
> exec "=" dcon
>
> This is fictitious of course, but would mean assign the values in [1] to
> [0].
> Yes, it would be easy to loop and assemble elements into a string that would
> be executed by exec (or eval), or use some assignment line like your
> example.
>
> I have 30 or more of such assignments, and I would prefer not to have to
> write them as assignments. The end purpose here is to produce a config file,
> assign initial values, and change values. For example, the (text) file might
> look initially like:
> long 120.00
> lat 39.00
> year 2009
Do you know about the ConfigParser module?
http://docs.python.org/library/configparser.html
> These would be written to the file by looping through dcon. Another time, I
> might want to initialize these variables within the program, in the form
> self.long = 120.00, etc.,
Ok, that is different than
long = 120.00
because the variable is an attribute of self. Try this, it will take
all the items in dcon and set them as attributes of self:
for key, value in dcon:
setattr(self, key, value)
Kent
More information about the Tutor
mailing list