Using eval() with Undefined Variables
<p>I want to create a Python script that takes in a string representation of a dictionary and outputs a list of tuples representing the items of the dictionary. The rub is, I want it to take in variables that have not been defined. An example illustrates this best:</p>

<p>Input: <code>{'test': test}</code></p>

<p>Output: <code>[('test': test)]</code></p>

<p>I've created some code to read in the dictionary and define the variables that haven't yet been defined, but when I <code>eval()</code> the result, it substitutes in the actual value of the variable rather than the variable name.</p>

<p>Here is the code:</p>

<pre><code>import sys
import re

if __name__ == "__main__":
    instr = sys.argv[1]
    success = False
    while not success:
        try:
            indict = eval(instr)
            success = True
        except NameError, e:
            defname = re.search("name '([^\']*)' is not defined", str(e))
            locals()[defname.group(1)] = 0
    print indict
</code></pre>

<p>I was hoping, for the above defined input value, that the dict it printed out would match the input string perfectly, but instead it has substituted in the value of 0 for <code>test</code>. Thus the script prints out:</p>

<pre><code>{'test': 0}
</code></pre>

<p>I have tried <code>ast.literal_eval</code>, but it throws a <code>ValueError: malformed string</code> for any variable name in the literal, even if it's been defined.</p>

<p>Thus, my question is: Is there a way to convert the input dictionary without losing the variable names?</p>
