I have a bunch of classes which I'm using as singletons / enums / dict keys, e. g. like this:
class Side(object): pass
class Left(Side): pass
class Right(Side): pass
def show_state(distribution):
print "left is", distribution[Left]
print "right is", distribution[Right]
distribution = { Left: 3, Right: 7 }
show_state(distribution)
This works fine for me. But I'm having a small issue with debug output I sometimes do. Normally I use just print
for this like in print distribution
in the show_state()
function. I would love to have an output like:
{ Left: 3, Right: 7 }
But when I do this with these classes they are given out as something like this:
{<class '__main__.Right'>: 7, <class '__main__.Left'>: 3}
I tried to override the __repr__()
method of my classes to achieve this, but when I do it only influences instances of my classes (which I never create). I tried to use @classmethod
and @staticmethod
but nothing worked.
I assume that what I print is a Left
and therefore an instance of <type 'type'>
, so I would have to override the __repr__()
method of the type
class which is immutable, unfortunately.
Is there any other trick I could use so that print distribution
would print what I want?
Btw, according to the documentation, the __repr__()
method should return something which the Python parser would turn into an equal object again; this is definitely not the case with an output like <class '__main__.Right'>
but would definitely be the case with an output like Right
.