One problem with this whole idea is that there can be some kinds of objects who's state is not fully dependent on the arguments given to its constructor. For a trivial case, consider a class with random state:
import random
def A(object):
def __init__(self):
self.state = random.random()
There's no way for this class to correctly implement __getnewargs__
, and so your implantation of __repr__
is also impossible. It may be that a class like the one above is not well designed. But pickle
can handle it with no problems (I assume using the __reduce__
method inherited from object
, but my pickle-fu is not enough to say so with certainty).
This is why it is nice that __repr__
can be coded to do whatever you want. If you want the internal state to be visible, you can make your class's __repr__
do that. If the object should be opaque, you can do that too. For the class above, I'd probably implement __repr__
like this:
def __repr__(self):
return "<A object with state=%f>" % self.state