uqfoundation / dill

serialize all of Python

Home Page:http://dill.rtfd.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

dump/load an object with the module where its class is defined

sdementen opened this issue · comments

I have a module defining a class. I have a script instantiating this class to get an object I want to dump.
However, I would like the dump to also contain the class/module so that loading the dump would not require the module to be defined.
(my use case is about a class representing a table in an ORM, a record of the table being an object of the class, and the table schema changing with time ==> I would like the object to be dumped with the class/table schema at the time it was extracted from the DB).

Example:

# today 2023/05/11 ---------------------------------------------
# file mymodule.py
class User:
  name: str

# file script_dump.py
from mymodule import User
u = User(name="Joe")
import dill
dill.dump(u, "user_20230511.pkl")

# in some distant future ---------------------------------------------
# file mymodule.py
class UserExtended: # the class has changed a bit
  first_name: str
  last_name: str

# file script_load.py
import dill
dill.load("user_20230511.pkl") # I would like to recover the User I dumped even though the User class has changed/disappeared or the module mymodule has changed/disappeared
# ==> will raise an Exception as the class User is not defined anymore in the mymodule.py
# ==> will raise an Exception also if the file mymodule.py is not there anymore
# Could dill dump the original mymodule & User objects at the same time as the object u to have a standalone pickle ?