gpt4 book ai didi

python - 在我的模块中导入一次外部包而不将其添加到命名空间

转载 作者:行者123 更新时间:2023-11-28 17:26:55 25 4
gpt4 key购买 nike

对于无法更轻松地表达我的问题,我深表歉意。我正在编写一个大包,几乎在每个功能中都广泛使用了 pandas。我的第一直觉自然是创建一个 __init__.py 作为

import pandas
# then import my own submodules and other things

然后,每次我在函数中使用 pandas 时,都从子模块中将其调用为 from 。 import pandas as pdfrom .. import pandas,或类似的东西。

但是,如果我这样做,当我加载我的包时,pandas 将显示为“子模块”,即,有一个 mypackage.pandas。这不会伤害任何人,但我猜是不正确的。避免这种情况的一种方法是在 __init__.py 的末尾添加一个 del pandas,这似乎也不是正确的方法。

所以从现在开始,我不会在我的 __init__ 中导入 pandas,而是在每个 -function- 中单独导入它,这样可以正常工作,但过于重复并且会阻止设置全局 pandas 设置。

这里首选的方法是什么?有没有我缺少的方法?

谢谢。

最佳答案

...by importing pandas from the __init__.py call I can define some pandas' options there (like pandas.options.display.expand_frame_repr) and it will be valid throughout the module.

无论如何,他们都会。该模块仅在您第一次调用 import pandas 时加载。此时,对该模块的引用存储在可通过 sys.modules 访问的模块字典中。在任何其他模块中对 import pandas 的任何后续调用都将重新使用来自 sys.modules 的相同引用,因此您更改的任何选项也将适用。

Furthermore, re-importing the same package from scratch seems to me that takes longer, but I'm not sure it that is correct.

它实际上应该稍微快一些,因为它不必解析相对路径。加载模块后,后续调用将像...

import pandas          # pandas = sys.modules['pandas']
import pandas as pd # pd = sys.modules['pandas']

关于python - 在我的模块中导入一次外部包而不将其添加到命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125727/

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