The rule of literal string

Chris Rebert clp at rebertia.com
Wed Dec 17 18:40:21 EST 2008


On Wed, Dec 17, 2008 at 3:34 PM, James Mills
<prologic at shortcircuit.net.au> wrote:
> On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert <clp at rebertia.com> wrote:
>> As I stated previously, the key rule is:
>>
>> eval(repr(something)) == something
>
> This rule is only true for basic data types;
>
> For example:
>
>>>> eval(repr(1)) == 1
> True
>>>> eval(repr([1, 2, 3])) == [1, 2, 3]
> True
>>>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3}
> True
>>>> eval(repr("foo")) == "foo"
> True
>
> I guess the key thing here is that the repr
> implementation (__repr__) for str, int, float
> list and dict return sensible represenations
> that Python _can_ evaluate with eval(...)
>
> --JamesMills
>

True, I oversimplified to make things easier to understand. Strictly
speaking, only the basic types make the guarantee I stated. Arbitrary
types can have arbitrary, non-eval()-able repr()s. But the docs do
state eval()-ability as a goal:

repr(object)
    Return a string containing a printable representation of an
object. [...] For many types, this function makes an attempt to return
a string that would yield an object with the same value when passed to
eval(), otherwise the representation is a string enclosed in angle
brackets that contains the name of the type of the object together
with additional information often including the name and address of
the object. A class can control what this function returns for its
instances by defining a __repr__() method.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list