Rolling a Container Into a String

Delaney, Timothy C (Timothy) tdelaney at
Fri Jun 25 09:21:00 CEST 2004

Terry Reedy wrote:

> "Kamilche" <klachemin at> wrote in message
> news:889cbba0.0406241742.51a2980b at
>> I want to convert a dict into string form, then back again. After
>> discovering that eval is insecure,
> With arbitrary code from an arbitrary source, yes.
> If you *know* that you are eval-ing your own safe strings, then no
> problem. 
>> I wrote some code to roll a Python
>> object, dict, tuple, or list into a string.
> repr(object) already does that for you.  Why duplicate the work?
> You only need custom a eval function, which might check that string
> is safe (no function calls, no list comps) and then eval, or which
> might do parsing and construction itself.

If you are also including non-core class instances which don't have an
eval-able repr string, you can use pickle.dumps and pickle.loads.

But to reiterate what Terry said - if you're producing the strings, and
you can store them securely enough, don't worry about the insecurities
in eval (and pickle).

Tim Delaney

More information about the Python-list mailing list