Dynamic variable creation from string
Peter Otten
__peter__ at web.de
Fri Dec 9 06:27:47 EST 2011
Massi wrote:
> for k in D : exec "%s = D[k]" %k
>
> That seems to do the trick, but someone speaks about "dirty code", can
> anyone point me out which problems this can generate?
exec can run arbitrary code, so everybody reading the above has to go back
to the definition of D to verify that it can only contain "safe" keys.
Filling D with user-input is right out because a malicious user could do
anything he likes. Here's a harmless demo that creates a file:
>>> d = {"x = 42\nwith open('tmp.txt', 'w') as f:\n f.write('whatever')\nx":
123}
>>> for k in d: exec "%s = d[k]" % k
...
>>> x
123
>>> open("tmp.txt").read()
'whatever'
More information about the Python-list
mailing list