[Tutor] Turning a string into a tuple? (Without eval?)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 27 Sep 2001 23:12:08 -0700 (PDT)


On Thu, 27 Sep 2001, Kirby Urner wrote:

> >asking.  Thank you for your time.
> >
> >Is there a searchable index to the python tutor list?
> 
> The various Python lists (including this one) are archived at
> ActiveState (as well as Python.org) and in the former case, are
> searchable by key word(s):
> http://aspn.activestate.com/ASPN/Python/Mail
> 
> Not always easy to find your topic of course, e.g. doesn't help to
> search on "string" :-D.

David's question is a very good one --- What happens if we want to avoid
using eval()?  We've always encouraged people to avoid it like the plague
because eval() is just way too powerful for normal use.


It would be nice if someone could write a small "parser" that translated a
string made up of:

    lists, strings, and numbers

into a Python data structure.

If we put on our "wishing makes it so" hat, we could imagine doing
something like this:

###
>>> parse("[1, 2, 'three']")
[1, 2, "three"]
>>> parse("[   1.0    , [[2]]  ]")
[1.0, [[2]]]
###

It would be cool if it could handle nested lists, as our imaginary parse()
does.  It's not a requirement, but it would be quite nice...

I haven't written this program yet, but it sounds like it might be really
useful for people who want to avoid the dangers of eval().  Does anyone
want a crack at it first?  *grin*