Alex Rivera | Logout

Why does the repr() of a string have two sets of quotes? And why don't I get the object back when I eval() it?

Asked 2011-10-16T12:07:55.503
162

repr(): evaluatable string representation of an object (you can eval() it, meaning it is a string representation that evaluates to a Python object)

In other words:

>>> x = 'foo'
>>> repr(x)
"'foo'"

Questions:

  1. Why do I get the double quotes when I do repr(x)? (I don't get them when I do str(x))
  2. Why do I get 'foo' when I do eval("'foo'") and not x which is the object?
Edit
Report

1 Answer

175

Consider:

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x), the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method, __repr__, of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it's the same as if we type 'foo' in the interpreter. It's as if we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it's the same as if we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>>
answered 2011-10-16T12:22:14.787

Your Answer