For a long time I have been puzzled by Alex Martelli's remark about:
(...) the fuzzy unattainable goal of making repr's returned value acceptable as input to eval!
So I gave it a try and came up with this:
class Sic():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.method_var = lambda x, y, z : x + y + z
def __repr__(self):
def right_quotes(value):
return repr(value).translate(str.maketrans('\'\"', '\"\''))
from inspect import signature
class_sig = signature(self.__class__)
fields = tuple('{}={}'.format(k,right_quotes(v)) for k,v in self.__dict__.items() if k in class_sig.parameters)
return self.__class__.__name__ + str(tuple(sorted(fields))).replace("\'","")
Is this a correct general implementation of __repr__
? If not could you give an example where it fails?
(I have improved the original version with the suggestion of Barmar, and responding to the objection of Kuco 23. I am looking here to a most general solution, even if it involves using introspection.)