February 2010 (1)
September 2009 (1)
May 2009 (1)
April 2009 (1)
March 2009 (4)
January 2009 (3)
November 2008 (2)
October 2008 (2)
September 2008 (1)
August 2008 (5)
July 2008 (3)
June 2008 (1)
May 2008 (5)
April 2008 (8)
March 2008 (3)
February 2008 (1)
January 2008 (2)
December 2007 (2)
November 2007 (4)
October 2007 (17)
September 2007 (9)
2007-10-10 20:32:58
When I write Python, sadly my code often has bugs. One way or another I always end up dumping out variables to see what’s in them. If those variables refer to objects, Python’s default representation is not very helpful:
>>> class C:
... def __init__(self, arg):
... self.member = arg
...
>>> obj = C('foo')
>>> print obj
<__main__.C instance at 0xb7d363ec>
It would be nice to have something that lets you know what’s inside that object
Python lets you help yourself. If you define __str__ and __repr__ methods on your classes, then they will have nice string representations when you want to print them, or when a debugger inspects them for you. This can be a bit laborious though, especially if you want to meet the requirement (see the docs) that __repr__ should return “a valid Python expression that could be used to recreate an object with the same value.” And as a good Python citizen, of course you want to do that.
I have a solution that won’t always be the right thing, but saves a lot of typing for many simple classes. I find that often I write classes that are really glorified dictionaries with a few helper methods. In my day job, where we mostly write Java, we work where possible with POJOs or beans. This seems like a Pythonic way to emulate and improve on that idiom.
def simplerepr(obj):
d = obj.__dict__
members = ', '.join([n + '=' + v.__repr__() for n,v in d.iteritems()])
return '%s(%s)' % (obj.__class__.__name__, members)
def attrsfromdict(d):
"""From Python cookbook s6.18 p 280"""
self = d.pop('self')
for n,v in d.iteritems():
setattr(self, n, v)
class Foo(object):
def __init__(self, arg1="wstfgl", arg2="sneeb!"):
attrsfromdict(locals())
def __str__(self):
return simplerepr(self)
def __repr__(self):
return self.__str__()
>>> f = Foo('quux')
>>> f
Foo(arg1='quux', arg2='sneeb!')
>>> g = Foo(arg1='quux', arg2='sneeb!')
>>> g
Foo(arg1='quux', arg2='sneeb!')
This was inspired by and builds on a recipe in the Python Cookbook.
Rendered at 2012-02-10 00:33:56