tags:

views:

121

answers:

3
a='''b="ddd"'''
eval(repr(a))
print str(a)
print b

Please try to use the code, rather than text, because my English is not very good, thank you

+2  A: 

Use:

eval(compile(a,'<string>','exec'))

instead of:

eval(repr(a))

Transcript:

>>> a='''b="ddd"'''
>>> eval(compile(a,'<string>','exec'))
>>> print str(a)
b="ddd"
>>> print b
ddd

The problem is that you're actually executing the statement 'b="ddd"' which is not an assignment to b but an evaluation of the string.

The eval() built-in, when given a string, evaluates it as an expression (not a statement) and returns the result. You can get eval() to run non-expression code by giving it a code object, which we create with compile() above. In that case it runs the code and returns None.

You can see a similar effect if you just enter:

>>> 'c=7'
'c=7'
>>> c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> c=7
>>> c
7
>>> '7=d'
'7=d'
>>> 7=d
  File "<stdin>", line 1
SyntaxError: can't assign to literal

Clearly 7=d is not valid Python, yet '7=d' is, for the reason explained above.

Descriptions of the expr(), repr() and compile() built-ins, adequate enough to work this out, were found here. No built-ins were harmed during the making of this answer.

paxdiablo
see also: http://docs.python.org/reference/simple_stmts.html#exec
Miles
+2  A: 

eval is used to evaluate (get the result of) an expression. What you want is dynamic execution of Python code, which is done with exec:

>>> a='''b="ddd"'''
>>> exec(a)
>>> print b
ddd

Also note that you should not call repr() before passing the string to either function. You already have a string, calling repr() creates a string representation of a string.

Andre Miller
A: 

Reconsider whether you really need to use eval(). For example, you can use globals() like this:

>>> globals()['b'] = 'ddd'
>>> print b
ddd

But perhaps what you should probably be using is just a dictionary:

>>> my_namespace = dict()
>>> my_namespace['b'] = 'ddd'
>>> my_namespace
{'b': 'ddd'}
>>> print my_namespace['b']
ddd
Miles