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

Importing external package once in my module without it being added to the namespace

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

import pandas
# then import my own submodules and other things

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

但是,如果我这样做,当我加载我的包时,pandas 显示为 "submodule",即有一个 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']