literal_eval of tuple with a single element
<p>I am using <code>ast.literal_eval(str)</code> to evaluate a string containing a tuple such as <code>('a', 'b', 'c')</code>. However, if for some reason this tuple only contains a single element, the expression ignores the parenthesis and returns only the element:</p>

<pre><code>&gt;&gt;&gt; string = "('a')"
&gt;&gt;&gt; x = ast.literal_eval(string)
&gt;&gt;&gt; x
'a'
</code></pre>

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

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

<pre><code>&gt;&gt;&gt; type('a')
&lt;type 'str'&gt;    &lt;-- String
&gt;&gt;&gt; type(('a'))
&lt;type 'str'&gt;    &lt;-- String
&gt;&gt;&gt; type(('a',))
&lt;type 'tuple'&gt;  &lt;-- Tuple
</code></pre>

python abstract-syntax-tree