MarEe MarEe - 4 months ago 17
Python Question

literal_eval of tuple with a single element

I am using

to evaluate a string containing a tuple such as
('a', 'b', 'c')
. However, if for some reason this tuple only contains a single element, the expression ignores the parenthesis and returns only the element:

>>> string = "('a')"
>>> x = ast.literal_eval(string)
>>> x

Is there a non-hackish way to solve this? This problem is exacerbated by the fact that sometimes, I might have a tuple of tuples, like
and as such cannot just check for type. Thanks!


That is because ('a') is not a tuple but a string treated as a. Tuple with only one object is defined as ('a',) (note the ,)

>>> type('a')
<type 'str'>    <-- String
>>> type(('a'))
<type 'str'>    <-- String
>>> type(('a',))
<type 'tuple'>  <-- Tuple