在我的模块中导入一次外部包而不将其添加到命名空间 [英] Importing external package once in my module without it being added to the namespace

查看:40
本文介绍了在我的模块中导入一次外部包而不将其添加到命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I apologize for not being able to phrase my question more easily. I am writing a large package that makes extensive use of pandas in almost every function. My first instinct, naturally, was to create an __init__.py as

import pandas
# then import my own submodules and other things

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

And then, every time I use pandas in a function, call it from the submodules as from . import pandas as pd or from .. import pandas, or something like that.

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

However, if I do this, when I load my package, pandas appears as a "submodule", i.e., there is a mypackage.pandas. Which doesn't hurt anyone, but I'm guessing is not correct. A way to avoid this would be adding a del pandas at the end of __init__.py, which also doesn't seem like the correct approach.

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

So from now on I don't import pandas in my __init__ and import it separately inside every -function-, which works fine, but is too repetitive and prevents me from setting global pandas settings.

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

What is the preferred approach here? Is there a method which I am missing?

谢谢.

推荐答案

...通过从 __init__.py 调用中 importing pandas 我可以定义一些 pandas'选项(如 pandas.options.display.expand_frame_repr),它将在整个模块中有效.

...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 的相同引用,因此您更改的任何选项也将适用.

They will be anyway. The module is only loaded the first time you call import pandas. At that point a reference to the module is stored in a module dictionary accessible via sys.modules. Any subsequent calls to import pandas in any other module will re-use the same reference from sys.modules, so any options you changed will also apply.

此外,在我看来,从头开始重新导入同一个包需要更长的时间,但我不确定这是正确的.

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

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

It should actually be marginally faster, since it doesn't have to resolve relative paths. Once the module has been loaded, subsequent calls work like...

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

这篇关于在我的模块中导入一次外部包而不将其添加到命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆