Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does loading a pickle import the object's module?

Tags:

python

pickle

I was under the impression that loading an object (that's not of one of the built-in types) from a pickle will import the module. For example, pickle can't import a module that exists? indicates that module correponding to the type of the object being unpicked must exist at the same path.

However, when I try to unpickle a NumPy ndarray, the unpickling worked fine, but the module does not seem to be imported:

In [12]: with open('numpysample.pkl', 'rb') as input:
    ...:     a = pickle.load(input)

In [14]: type(a)
Out[14]: numpy.ndarray

In [13]: numpy
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-8d40275025d1> in <module>
----> 1 numpy

NameError: name 'numpy' is not defined

What's going on here?

like image 401
rishai Avatar asked Jun 07 '26 01:06

rishai


1 Answers

Pickle imports the module. Just not into that name space. 'numpy' in sys.modules will be false before the pickle.load call and true after.

is it correct to say that there is no namespace into which numpy is imported?

The source of pickle.Unpickler.find_class should answer this.

    def find_class(self, module, name):
        # Subclasses may override this
        __import__(module)
        mod = sys.modules[module]
        klass = getattr(mod, name)
        return klass

During this method the module those name is in module is bound to mod during the scope of this function.

like image 79
Dan D. Avatar answered Jun 08 '26 16:06

Dan D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!