Variable definition

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 26 22:33:57 EST 2010


On Fri, 26 Feb 2010 15:32:27 -0800, Raphael Mayoraz wrote:

> 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.


The Right answer is:

Don't do that. How can you use a variable without knowing its name?

Suppose you do this:

for key, value in varDic.iteritems():
    'myPrefix_' + key = value

and then later you want:

print myPrefix_blue

But hang on. How could you possibly know it is called myPrefix_blue and 
not myPrefix_cyan or myPrefix_turquoise?

You can't possibly know, so in general defining a named variable is 
useless. What you want instead is:

some_colour = 'blue'  # get this at runtime
print varDic[some_colour]

You don't even need the myPrefix, but if you really want it:

for key, value in varDic.iteritems():
    varDic['myPrefix_' + key] = value
    del varDic[key]

some_colour = 'blue'  # get this at runtime
print varDic['myPrefix_' + some_colour]

or any one of a million variations on this idea.

For some very, very rare situations you might need to programatically 
define variables. The right way to do that is:

globals()['myPrefix_turquoise'] = 42

or 

setattr(module, 'myPrefix_turquoise'] = 42

or even:

exec "'myPrefix_turquoise' = 42"

but if you are thinking of using that last one with data coming from an 
untrusted user (and nearly all users are untrusted!), then DON'T. That is 
a huge security hole. And it's also very slow.



-- 
Steven



More information about the Python-list mailing list