This is a follow up of my previous question : Enum comparison become False after reloading module
Ultimately, I would like to be able to pickle my enum.
Let's start from myenum.py
again :
# myenum.py
import enum
class MyEnum(enum.Enum):
ONE = 1
TWO = 2
I again import this file in my script. I create a variable a
an instance of MyEnum
, pickles it and load it into a variable b
. It works fine and both variables are equal.
Now, I reload my file. I try to pickle a
but the following error occurs :
Traceback (most recent call last):
File "f:/python_test/test.py", line 8, in <module>
b = pickle.loads(pickle.dumps(a))
_pickle.PicklingError: Can't pickle <enum 'MyEnum'>: it's not the same object as myenum.MyEnum
I believe this is because the IDs of the enum changed, so in pickle
eyes, a
is indeed not the same object.
Note that it is not a solution for me to redefine each existing enum variable each time a file is reimported.
Here is the code to reproduce the issue :
# test.py
import importlib, myenum, pickle
if __name__=='__main__':
a = myenum.MyEnum.ONE
b = pickle.loads(pickle.dumps(a))
print(b == a) # is True
importlib.reload(globals()["myenum"])
b = pickle.loads(pickle.dumps(a)) # Error
print(b == a)