[Python-ideas] Round-trippable repr for everything

Random832 random832 at fastmail.com
Wed Feb 10 15:29:24 EST 2016


On Tue, Feb 9, 2016, at 03:56, Cory Benfield wrote:
> I think the reality is that there is no constraint on the representation
> of arbitrary types to be round-trippable in any way. Again, all custom
> types have non-round-trippable representations by default, many more
> eclectic built-in types have non-round-tripppable representations (in
> addition to NaN, the memoryview object leaps to mind).

One other example is classes and functions though in many cases it's not
clear why this should be the case. Have the default for top-level
functions and classes check whether it's reachable through
[module].[name] and if so return that. The default for methods could use
[class].[name], or [obj].[name] for bound methods.

Instead of the current representation, you could have the default repr
on objects use pickle.

def __repr__(self):
    return 'pickle.loads(%r)' % pickle.dumps(self)

Or maybe have a helper function e.g.

def unrepr(description, pickled)
    return pickle.dumps(pickled)  # ignore description

and default to "unrepr('MyClass object at 0x12345678', b'pickledstuff')"

[Speaking of pickle and since you mentioned memoryview, I noticed a bug:
pickle apparently successfully generates output for a memoryview, but it
fails on attempting to unpickle it - I think that it should throw an
exception immediately on attempting to pickle it.]

Certainly there's the odd edge case where it doesn't make sense for it
to be round-trippable, and there's a tradeoff between human-readability
and round-trippability (see e.g. all the classes that can't be
round-tripped unless the class is imported)... but that's part of where
a short-repr vs long-repr could make sense - short-repr could
Decimal('123.456') or even <Decimal 123.456> whereas long-repr returns
__import__('decimal').Decimal('123.456')


More information about the Python-ideas mailing list