Most probably a stupid question, but I still want to ask

Rustom Mody rustompmody at gmail.com
Mon Apr 11 02:57:54 EDT 2016


On Monday, April 11, 2016 at 11:12:39 AM UTC+5:30, Stephen Hansen wrote:
> On Sun, Apr 10, 2016, at 10:18 PM, Rustom Mody wrote:
> > On Monday, April 11, 2016 at 10:17:13 AM UTC+5:30, Stephen Hansen wrote:
> > > On Sun, Apr 10, 2016, at 09:03 PM, Fillmore wrote:
> > > > and the (almost always to be avoided) use of eval()
> > > 
> > > FWIW, there's ast.literal_eval which is safe and there's no reason to
> > > avoid it.
> > 
> > Its error reporting is clunky:
> > 
> > >>> from ast import literal_eval as le
> > >>> le("(1)")
> > 1
> > >>> le("(1,)")
> > (1,)
> > >>> le("1")
> > 1
> > >>> le("{1:x}")
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> >   File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
> >     return _convert(node_or_string)
> >   File "/usr/lib/python2.7/ast.py", line 63, in _convert
> >     in zip(node.keys, node.values))
> >   File "/usr/lib/python2.7/ast.py", line 62, in <genexpr>
> >     return dict((_convert(k), _convert(v)) for k, v
> >   File "/usr/lib/python2.7/ast.py", line 79, in _convert
> >     raise ValueError('malformed string')
> > ValueError: malformed string
> 
> So? Worst case scenario, someone puts invalid data into the file and it
> throws an exception. Could it be more specific? Maybe, but I don't see
> why it needs to be. If your input isn't reliably formatted, catch
> ValueError and log it and fix (either what wrote it or change how you
> read it).

Sorry... Didnt mean "dont use!"
Just "Heres a flipside to consider"
Also that the OP's question is not a classic "Avoid eval like the plague"
but "Many nooks and crannies in the syntax" issue



More information about the Python-list mailing list