dynamic assigments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 24 19:18:04 EDT 2011


On Thu, 24 Mar 2011 14:39:34 -0700, scattered wrote:

> Could try:
> 
>>>> my_list = [("x", 7), ("y", 8)]
>>>> for pair in my_list: exec(pair[0] + " = " + str(pair[1]))
>>>> x,y
>>>> (7,8)


Please don't ever do such a thing. The world has enough buggy software 
vulnerable to code injection attacks without you encouraging newbies to 
write more.

If (generic) you, the programmer, can write 

my_list = [("x", 7), ("y", 8)]
for pair in my_list:
    exec(pair[0] + " = " + str(pair[1]))


in your code, then you should stop messing about and just write:

x = 7
y = 8

instead. The only time this technique is even *possibly* justified is if 
the contents of my_list comes from external data not known at compile-
time. But that means you're vulnerable to a hostile user injecting code 
into your data:

my_list = [("import os; os.system('echo \"deleting all files...\"'); x", 
7), ("y", 8)]
for pair in my_list:
    exec(pair[0] + " = " + str(pair[1]))


Code injection attacks are some of the most common source of viruses and 
malware, far more common (and much easier to perform!) today than buffer 
overflows. If an unprivileged process can inject code into something that 
a privileged process is running, your computer is compromised.



-- 
Steven



More information about the Python-list mailing list