MarEe
MarEe

Reputation: 23

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!

Upvotes: 2

Views: 972

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

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

Upvotes: 2

Related Questions