MarEe MarEe - 3 months ago 11
Python Question

literal_eval of tuple with a single element

I am using

ast.literal_eval(str)
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
'a'


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
(('a','b'))
and as such cannot just check for type. Thanks!

Answer

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
Comments