String2List: odd function

Isidor rodisi01 at my-deja.com
Tue Jul 27 18:54:02 EDT 1999


Hello all -

In response to my nice offer of a strange function that in ~80 lines 
of code slices and dices your list-like strings into *real* lists, I 
received three nice replies pointing out that the same thing could be 
done in ~1 line. Wow. Talk about optimization!:

From:           	Gaetan Corneau <Gaetan_Corneau at baan.com>

> >>> s = '[1, 2, 3, 4, 5, ["a", "b", "c"], 6, 7, 8]'
> >>> s = "l = " + s
> >>> exec(s)
> >>> l
> [1, 2, 3, 4, 5, ['a', 'b', 'c'], 6, 7, 8]

From:           	"Fredrik Lundh" <fredrik at pythonware.com>

> v = eval(s, {"__builtins__": {}})


From:           	"Emile van Sebille" <emile at fenx.com>
 
> >>> a = eval ("[['itema1', 'itema2'], 'itemb1', ['cheese1',
> ['cheese1a','cheese1b'], '2'], 'blah', 'rest of itemb2', 'zib']")
> >>> a
> [['itema1', 'itema2'], 'itemb1', ['cheese1', ['cheese1a', 
'cheese1b'], 
> '2'], 'blah', 'rest of itemb2', 'zib']
> 

When I read these messages, the first thing I thought was: "wow! 
*that's* what exec and eval do?!" I had read about them in the 
documentation, and I suspected that they were important, but I 
couldn't figure out what the heck they really did. A few unsuccessful 
experiments didn't help much either. Well, now I know a little more. 
However, I suspect that this use is not among the common uses for 
which exec and eval were designed. Would you be willing to reply with 
some examples of how you use these functions normally? What are they 
*really* used for? (As I collect more of these examples from others 
and from my own banging around, they will go on a web page w. 
credits, of course, to the example providers...and then someday...I 
will join the PSA...and then...and then...)

Thanks for setting me straight, and thanks in advance for any 
examples!

Isidor




More information about the Python-list mailing list