Skip to content

Instantly share code, notes, and snippets.

@HacKanCuBa
Created March 1, 2022 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HacKanCuBa/30a04c1b02b72d5a6b4a8fa702d9b963 to your computer and use it in GitHub Desktop.
Save HacKanCuBa/30a04c1b02b72d5a6b4a8fa702d9b963 to your computer and use it in GitHub Desktop.
How pickle changes according to how the interpreter gets called
"""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