[SciPy-Dev] Custom __repr__?

Andrew Nelson andyfaff at gmail.com
Thu May 13 21:02:06 EDT 2021


>
> Having a proper __repr__ that allows to recreate objects is nice, but
> serialization seems to be a misuse of __repr__. We have the __getstate__
> __setstate__ mechanism in Python for serialization. Could you explain your
> use case a bit more for my curiosity?
>

It's the recreation of objects that I wanted to have. My use case is for a
piece of code that's running in a PyQt5 GUI to output a standalone Python
script that can then be executed separately (on a cluster). The script has
to recreate an Object that has a few layers of complexity (Objective -->
Model --> Structure --> Layers --> Parameters --> Parameter --> Bounds). By
implementing a __repr__ for all of those it allows me to call
`repr(Objective)` to create the script. The Bounds are more than likely a
uniform distribution, which I've implemented myself for speed, but they can
also be any scipy.stats.rv_continuous distribution. At the moment I can't
recreate rv_continuous from their __repr__.

I suppose I could create a script and associated pickle file, with the
script loading the pickle file. This will be less robust/reproducible, both
laterally and vertically (laterally = use at same time, but on different
machine, with roughly similar Python environment; vertically = use N years
later). The main issue with vertically is that new attributes may get added
to classes which means that unpickling issues often occur because the
pickle doesn't possess the new attributes. Writing out classes with a
__repr__ doesn't have that issue because they're created from scratch.

There is a slightly different aspect to this kind of issue which is also
important to me, saving the state of a GUI program. At the moment I save
the state of the GUI into a pickle, but that's not necessarily readable in
later versions of the program because of the forwards compatibility of the
pickle against updated classes. I'd be interested in knowing how to
serialise these kinds of complex structures into something that's e.g.
json/text file based.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/scipy-dev/attachments/20210514/849b4eec/attachment.html>


More information about the SciPy-Dev mailing list