Best practise implementation for equal by value objects

Slaunger Slaunger at gmail.com
Thu Aug 7 02:21:03 EDT 2008


On 6 Aug., 21:46, John Krukoff <jkruk... at ltgc.com> wrote:
> On Wed, 2008-08-06 at 05:50 -0700, Slaunger wrote:
> > Hi,
>
> > I am new here and relatively new to Python, so be gentle:
>
> > Is there a recommended generic implementation of __repr__ for objects
> > equal by value to assure that eval(repr(x)) == x independet of which
> > module the call is made from?
>
> > Example:
>
> > class Age:
>
> >     def __init__(self, an_age):
> >         self.age = an_age
>
> >     def __eq__(self, obj):
> >         self.age == obj.age
>
> >     def __repr__(self):
> >         return self.__class__.__name__ + \
> >                "(%r)" % self.age
>
> > age_ten = Age(10)
> > print repr(age_ten)
> > print eval(repr(age_ten))
> > print eval(repr(age_ten)).age
>
> > Running this gives
>
> > Age(10)
> > Age(10)
> > 10
>
> > Exactly as I want to.
>
> > The problem arises when the Age class is iomported into another module
> > in another package as then there is a package prefix and the above
> > implementation of __repr__ does not work.
>
> > I have then experimented with doing somthing like
>
> >     def __repr__(self):
> >         return self.__module__ + '.' + self.__class__.__name__ +
> > "(%r)" % self.age
>
> > This seems to work when called from the outside, but not from the
> > inside of the module. That is, if I rerun the script above the the
> > module name prefixed to the representation I get the following error
>
> > Traceback (most recent call last):
> >   File "valuetest.py", line 15, in <module>
> >     print eval(repr(age_ten))
> > __main__.Age(10)
> >   File "<string>", line 1, in <module>
> > NameError: name '__main__' is not defined
>
> > This is pretty annoying.
>
> > My question is: Is there a robust generic type of implementation of
> > __repr__ which I can use instead?
>
> > This is something I plan to reuse for many different Value classes, so
> > I would like to get it robust.
>
> > Thanks,
> > Slaunger
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Are you really sure this is what you want to do, and that a less tricky
> serialization format such as that provided by the pickle module wouldn't
> work for you?

Well, it is not so much yet for serialization (although i have not yet
fully understood the implications), it is more because
I think the eval(repr(x))==x is a nice unit test to make sure my
constructor and equals method is implemented correctly (that I have
rememebered all attributes in their implementations).

As mentioned above, I may go for a more pragmatic approach, where i
only use repr if it "standard" imported

Cheers,
Slaunger

>
> --
> John Krukoff <jkruk... at ltgc.com>
> Land Title Guarantee Company- Skjul tekst i anførselstegn -
>
> - Vis tekst i anførselstegn -




More information about the Python-list mailing list