Bad programming style?
Gordon McMillan
gmcm at hypernet.com
Wed Dec 22 09:54:48 EST 1999
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.
You can do it and you probably shouldn't. The problem is
referencing it. How do you know what name to reference? If it
hasn't been created, you'll get a NameError.
You probably should use a dictionary (namespaces in Python
are dictionaries anyway(*)). That gives you syntax for looking
for a non-existant name without taking a NameError, and an
easy way to list out all the names you've created.
myvars = {}
if myvars.has_key('spam'): ...
value = myvars.get('spam', None) #None if doesn't exist
for var in myvars.keys(): ...
(*) The "locals" namespace is conceptually a dictionary, but
gets optimized into something else.
You can use a dummy class for syntactic sugar:
class Dummy:
pass
myvars = Dummy()
myvars.spam = 'eggs'
if hasattr(myvars, 'spam'): ...
for var in dir(myvars):
Be wary of "trying" too hard to do something dynamic. Python
usually has a very direct way of doing it.
- Gordon
More information about the Python-list
mailing list