dynamic assigments

Jason Swails jason.swails at gmail.com
Thu Mar 24 23:24:06 EDT 2011


On Thu, Mar 24, 2011 at 4:05 PM, Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:

> On Thu, 24 Mar 2011 19:39:21 +0100, Seldon wrote:
>
> > Hi, I have a question about generating variable assignments dynamically.
> [...]
> > Now, I would like to use data contained in this list to dynamically
> > generate assignments of the form "var1 = value1", ecc where var1 is an
> > identifier equal (as a string) to the 'var1' in the list.
>
> Why on earth would you want to do that?
>

Doesn't optparse do something like that?  (I was actually looking for a way
to do this type of thing)  OptionParser.add_option() etc. etc. where you add
a variable and key, yet it assigns it as a new attribute of the Options
class that it returns upon OptionParser.parse_args().

I would see this as a way of making a class like that generalizable.  I
agree that __main__ (or something contained within) would certainly need to
know the name of each variable to be even remotely useful, but that doesn't
mean that each part inside does as well.

It's certainly doable with dicts and just using key-pairs, but i'd rather do
something like

opts.variable

than

opts.dictionary['variable']

Just my 2c.  Thanks to JM for suggesting setattr, btw.

--Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110324/f525c7a5/attachment.html>


More information about the Python-list mailing list