default repr?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jul 23 02:24:54 CEST 2012


On Mon, 23 Jul 2012 08:54:00 +1000, Chris Angelico wrote:

> On Mon, Jul 23, 2012 at 8:48 AM, Dan Stromberg <drsalists at gmail.com>
> wrote:
>> If a class has defined its own __repr__ method, is there a way of
>> getting the default repr output for that class anyway?

If the class, call it C, is a subclass of some other class (or classes), 
then there is also the repr of the parent. You can get to that by calling 
parent.__repr__(instance), although there are some subtleties.

In Python 2, there are old-style or classic classes that don't inherit 
from anything else. I don't believe there is any way to get the repr of a 
classic class with no __repr__ method *except* from an instance with no 
__repr__ method. So the answer for C below will be No:

# Python 2.x
class C:
    def __repr__(self):
        return "C()"


But for new-style classes in Python 2, or all classes in Python 3, the 
answer is Yes. All classes inherit from object, directly or indirectly, 
so you can either call the object repr or use super:

# Python 2.x or 3.x
class K(object):  # inheriting from object makes it "new style"
    def __repr__(self):
        # but please don't do this -- see below for a better way
        print(object.__repr__(self))
        return "K()"

You can specify the parent class directly by name, as above, grab its 
__repr__ method, and call it. But that's the wrong solution: it does not 
work correctly with multiple inheritance, and even if you don't use MI 
yourself, it means that nobody else can use your class for MI.

Better is to allow Python to work out which parent class you have, even 
if you already know the answer and only have one parent. The dance is a 
little more complex, but now you are multiple-inheritance-safe:

# Python 2.x or 3.x
class K(object):
    def __repr__(self):
        # this ONLY works for new-style classes
        print(super(K, self).__repr__())
        return "K()"

Python 3 offers some additional magic: if you don't give super() any 
arguments, the compiler magically does the right thing:

# Python 3.x
class K(object):  # or just "class K"
    def __repr__(self):
        print(super().__repr__())
        return "K()"


> Methods are just functions, and you can call any method of any class
> with any object as its first parameter.

Not quite: they have to be an instance of that class.


> object.__repr__(some_object)

That will work because everything is an instance of object (apart from 
classic classes in Python 2).


> Though this mightn't work with everything. I wasn't able to paint a list
> as a tuple - "tuple.__repr__([1,2,3])" threw a TypeError. Oh well.
> There's a limit to the ways Python lets you shoot yourself in the foot.

Of course -- [1,2,3] is not a tuple, so how would tuple know what to do 
with it?



-- 
Steven



More information about the Python-list mailing list