Variable definition

Alf P. Steinbach alfps at
Sat Feb 27 01:22:24 CET 2010

* Raphael Mayoraz:
> Hello,
> I'd like to define variables with some specific name that has a common 
> prefix.
> Something like this:
> varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}
> for key, value in varDic.iteritems():
>    'myPrefix' + key = value
> I know this is illegal, but there must be a trick somewhere.

In general you'll IMHO be better off with the variables as attributes of an object.

If you want them to be modifiable then you can do

   class Whatever: pass

   myPrefix = Whatever()
   myPrefix.a = 'a'
   myPrefix.b = 'b'
   myPrefix.c = 'c'

If you want them to be sort of constants (weasel words intentional) then you 
might do (Python 3.x)  --  disclaimer: off-the-cuff & I'm not sure if that 
function is called 'namedtuple' but I think you'll find it anyway  --

   import collections

   Color = namedtuple( "Color", "red green blue" )
   myPrefix = Color( 'a', 'b', 'c' )

Cheers & hth.,

- Alf

More information about the Python-list mailing list