Bad programming style?

Grant Edwards grant at nowhere.
Wed Dec 22 11:11:45 EST 1999


In article <Pine.WNT.4.21.9912221356150.214-100000 at wks_3.e-shopwork.com>, Sposhua wrote:

>I'm sure this is bad programming (though I'm sure I'll be proved wrong), but I'd
>like to know how to do it anyway...
>
>I want to create a varaible name and use it as a normal variable, something
>like:
>
>c=['r','g','b']
>VARIABLE_CALLED(c[0])='ff'
>
>obviously there are ways around it using dictionaries or whatever, but I'd like
>to know if it's possible to actually _create_ this variable r='ff' 'on the
>fly'. And can anyone tell me if it actually has any use.

Yes, you can do this in Python by creating the string "r =
'ff'" and then executing it with "exec" or eval().  Any
language that can execute data can do this -- Lisp is probably
the most (in)famous example.  It's an extremely powerful tool.

[TNT is an extremely power tool.  But, if you're planting
petunias I recommend a spade: it's not as exciting, but it's
easier to control the size of the hole, and you're not as
likely to loose a limb.]

Likewise, executing dynamically generated program code can at
times be useful, but it's an easy way to have your program blow
up in your face.

OTOH, In Python you can (IIRC) create separate local and global
namespaces for use by the code you run using exec or eval --
that should act as a good firewall: preventing a lot of
collateral damage to your program's state-space when the
inevitible does happen.

Have fun, and remember to wear eye protection...

-- 
Grant Edwards                   grante             Yow!  I feel real
                                  at               SOPHISTICATED being in
                               visi.com            FRANCE!



More information about the Python-list mailing list