Executing a string as python code

Gerhard Häring gh_pythonlist at gmx.de
Wed Oct 24 08:31:05 EDT 2001


On Wed, Oct 24, 2001 at 07:01:24AM -0500, Stephen Boulet wrote:
> Yes, but this is no cgi script. It's in my program, which, after all, also 
> executes python code.
> 
> If I write:
> 
> <<
> command = ''
> for i in range(100):
>     command = command + 'list%d = []\n' % i
> 
> exec(command)
> 
> >>
> 
> That's no less secure than typing them out by hand, right?

In this particular case, it isn't less secure. Only slower and uglier.
I'd very much prefer to have a deeply nested data structure instead of
code generation like this one. If the data structure is too deeply
nested, the algorithm can often be made clearer by splitting it up into
several functions.

With the above snippet, you're introducing new problems: from the bunch
of generated variables, you don't know how many of them there are, for
example. With a list, you'd only need to call len(list).

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list