对于无法更轻松地表达我的问题,我深表歉意。我正在编写一个大包,几乎在每个功能中都广泛使用了 pandas。我的第一直觉自然是创建一个 __init__.py
作为
import pandas
# then import my own submodules and other things
然后,每次我在函数中使用 pandas 时,都从子模块中将其调用为 from 。 import pandas as pd
或 from .. import pandas
,或类似的东西。
但是,如果我这样做,当我加载我的包时,pandas 将显示为“子模块”,即,有一个 mypackage.pandas
。这不会伤害任何人,但我猜是不正确的。避免这种情况的一种方法是在 __init__.py
的末尾添加一个 del pandas
,这似乎也不是正确的方法。
所以从现在开始,我不会在我的 __init__
中导入 pandas,而是在每个 -function- 中单独导入它,这样可以正常工作,但过于重复并且会阻止设置全局 pandas 设置。
这里首选的方法是什么?有没有我缺少的方法?
谢谢。
最佳答案
...by
import
ingpandas
from the__init__.py
call I can define somepandas
' options there (likepandas.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/