-
-
Save amir-shehzad/5ed7ff0dac8e8fbabf3fb687c64c30cd to your computer and use it in GitHub Desktop.
How pickle changes according to how the interpreter gets called
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Pickle dumps test. | |
When pickle dumps a class, it will include the FQDN for the module. In this example, | |
we see how an imported class gets dumped including its module information, whereas | |
a local one has the current module name, which could be `__main__` or other depending | |
on how the interpreter was called! | |
If you save this file as `pickle_deal.py` and then in a python terminal you import it | |
`import pickle_deal`, you will see the following printed: | |
b'\x80\x04\x95)\x00\x00\x00\x00\x00\x00\x00\x8c\x0bpickle_deal\x94\x8c\x07Decimal\x94\x93\x94\x8c\x07123.456\x94\x85\x94R\x94.' | |
b'\x80\x04\x95%\x00\x00\x00\x00\x00\x00\x00\x8c\x07decimal\x94\x8c\x07Decimal\x94\x93\x94\x8c\x07123.456\x94\x85\x94R\x94.' | |
If you otherwise run the file with `python3 pickle_deal.py`, you will see the same as | |
running this code in a python interpreter: | |
b'\x80\x04\x95&\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x07Decimal\x94\x93\x94\x8c\x07123.456\x94\x85\x94R\x94.' | |
b'\x80\x04\x95%\x00\x00\x00\x00\x00\x00\x00\x8c\x07decimal\x94\x8c\x07Decimal\x94\x93\x94\x8c\x07123.456\x94\x85\x94R\x94.' | |
This implies that when pickling local classes, one must be careful on the way the | |
module gets called, otherwise the result of the pickling could differ. | |
""" | |
import pickle | |
from decimal import Decimal as NonLocalDecimal | |
class Decimal(NonLocalDecimal): | |
pass | |
value = '123.456' | |
print(pickle.dumps(Decimal(value))) | |
print(pickle.dumps(NonLocalDecimal(value))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment