Dynamic list name from a string

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 20 05:32:13 EST 2010


On Mon, 20 Dec 2010 02:08:57 -0800, MarcoS wrote:

> Hi, I need to create a list with a dynamic name, something like this:
> 
> '%s_list' %my_dynamic list = []
> 
> It's this possible?

I'm pretty sure you don't *need* to, you just think you do. It is highly 
unlikely that there is anything you can do with such a variable-variable-
name that you can't do by a more sensible technique.

But since you ask:


>>> name = 'variable'
>>> variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'variable' is not defined
>>> globals()[name] = "this is a bad idea, don't do it"
>>> variable
"this is a bad idea, don't do it"


Here's another way:


>>> del variable
>>> exec("%s = 'this is an even worse idea, be careful with this'" % name)
>>> variable
'this is an even worse idea, be careful with this'



Seriously, you probably shouldn't do this. The first is harmful because 
it leads to confusing, complicated, unclear code that is hard to 
maintain; the second is harmful for the same reasons, *plus* it is 
slower, AND could lead to serious security bugs. Google on "code 
injection attack" for more information.



(There are uses for these techniques, or at least similar techniques, but 
they are rare, fairly advanced, and quite specialised.)

-- 
Steven



More information about the Python-list mailing list