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 > You'll still have to deal with the fact that a single string > on a line will return a string while multiples will return a tuple, but > how you're doing that (checking the type of the result) is fine. Yes... 0 and 1 length tuples are special cases even if we argue till we are blue in the face To Fillmore: Go via lists and the special cases can be obviated: >>> def br(s): return "[" + s + "]" >>> s0="" >>> s1="1" >>> s2="1,2" >>> le(br(s0)) [] >>> le(br(s1)) [1] >>> le(br(s2)) [1,2] Then tuplify (if you so wish) >>> tuple(le(br(s0))) () >>> tuple(le(br(s1))) (1,) >>> tuple(le(br(s2))) (1, 2) -- https://mail.python.org/mailman/listinfo/python-list