gpt4 book ai didi

python - 加载 pickle 会导入对象的模块吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:59 24 4
gpt4 key购买 nike

我的印象是从 pickle 加载对象(不是内置类型之一)将导入模块。例如, pickle can't import a module that exists?指示与被取消拾取的对象类型对应的模块必须存在于同一路径中。

但是,当我尝试解开一个 NumPy ndarray 时,解开工作正常,但模块似乎没有被导入:

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

这是怎么回事?

最佳答案

Pickle 导入模块。只是不进入那个 namespace 。 sys.modules 中的“numpy”pickle.load 调用之前为 false,在调用之后为 true。

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

pickle.Unpickler.find_class 的来源应该回答这个问题。

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

在此方法期间,那些名称位于 module 中的模块在此函数范围内绑定(bind)到 mod

关于python - 加载 pickle 会导入对象的模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59149054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com