I’m trying to understand how pickling works so that I can correctly design the organization of my repository. Essentially, I pickle objects of type A
, whose instances contain objects of type B
. A
and B
are defined in modules in separate packages:
project_dir
|
|-- package_a
|
|-- module_a # class A is defined here
|
|-- package_b
|
|-- module_b # class B is defined here
I did an experiment that I expected to fail, given my knowledge about how pickling works, but it didn’t throw an exception:
module_a.py
:
class A:
name = "A"
module_b.py
:
class B:
def __init__(self) -> None:
self.a = None
In one terminal window:
project_dir> python
>>> import pickle
>>> from package_a.module_a import A
>>> from package_b.module_b import B
>>> b_obj = B()
>>> b_obj.a = A()
>>> b_obj.a.name
'A'
>>> with open("b.pickle", "wb") as f:
... pickle.dump(b_obj, f)
...
>>> exit()
In a new terminal window:
project_dir> python
>>> import pickle
>>> from package_b.module_b import B
>>> with open("b.pickle", "rb") as f:
... b_obj = pickle.load(f)
...
>>> b_obj.a.name
'A'
How is pickle
able to construct an A
object when I haven’t imported module_a
anywhere?
1