string to list? possible?

Alex Martelli aleax at aleax.it
Sun Jan 20 15:50:46 EST 2002


Aahz Maruch wrote:
        ...
>>>> eval("[1, 2, 3, 4]")
> [1, 2, 3, 4]
> 
> The problem is that there's no error checking, and if you're accepting
> input from a possibly-hostile source, it could muck with your program or
> data files.

Right, so:

def string_to_list(astring):
    import rexec
    try: return rexec.RExec().r_eval(astring)
    except SystemExit:
        raise RuntimeError("the nasty string tried to exit...")

this raises exceptions if astring is syntactically invalid or tries to do
nasty things (however, there's no guarantee at all that the returned
value, if no exceptions are returned, IS indeed a string).  I just
transform a SystemExit into a RuntimeError, as an example of
the exception-manipulation that you may want to do here.


Alex




More information about the Python-list mailing list