How to use __repr__ to create new object from it?
Asked Answered
P

2

11

This is something I don't really get. I am trying to use __repr__ to create a new object from its output.

I have a class, OrderedSet, which contains a list and methods to organize it. The str method of this class is

def __str__(self):
    s = "Set contains: "
    for elem in self.list: s += (" '" + elem + "'")
    return s

Now I am supposed to use __repr__ in a way to instanciate a new object from it. Like Orderedset second = repr(first)

Can I just do it like this?

def __repr__(self):
    return self.list.__str__()
Poul answered 8/1, 2014 at 13:2 Comment(2)
With eval(repr(some_object))? See e.g. here.Tzong
As a side note: list is a bad variable name since there is a builtin function of the same name.Tzong
T
7

The idea behind "using __repr__ to create new objects" is that the output of __repr__ can be valid python code, which, when interpreted with eval, creates (a copy of) the original object. For example, repr("foo") return "'foo'" (including the quotes), or repr([1,2,3]) returns '[1, 2, 3]'.

In your example you probably need something like this:

def __repr__(self):
    return "OrderedSet(%r)" % self.list

as well as a corresponding constructor:

def __init__(self, elements):
    self.list = elements

This way, repr(OrderedSet([1,2,3])) returns the string OrderedSet([1,2,3]), which, when evaluated, will invoke the contructor and create a new instance of the class.

Tzong answered 8/1, 2014 at 13:19 Comment(0)
I
5

No. __repr__() has to return a string or a lot of code would break.

Try this approach: __repr__() should return valid Python code. That would allow you to

second = eval(repr(first))

That said, the whole idea looks dubious. It feels like you try to come up with a clever way to serialize or clone objects.

Use pickling for serialization or maybe the json module. To clone, use a copy constructor.

Ironware answered 8/1, 2014 at 13:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.