【问题标题】:Top level imports supersede lower level imports?顶级进口取代低级进口?
【发布时间】:2022-07-16 19:19:15
【问题描述】:
在一个 jupyter 笔记本中,我有
import modin.pandas as pd
import utils
utils.py 有 import pandas as pd
utils.py 中的 pd 是否导入 pandas 或 modin.pandas?如果是前者,我有没有办法让 utils.py 使用 jupyter 笔记本中的 modin.pandas,而不在 utils.py 的代码中更改它
标签:
python
pandas
import
modin
【解决方案1】:
utils 模块将始终导入pandas as pd,即使您在另一个模块中导入modins.pandas as pd,在另一个模块中使用utils 模块也不会改变这一点。这是因为符号pd与模块字典相关联,而这个模块字典与另一个模块的字典是隔离的,这本质上代表了为不同模块提供不同命名空间的核心思想。
在utils 中使用modins.pandas 的方法是更新符号pd。您可以通过使用 setattr 方法将旧符号替换为新符号来轻松完成此操作:
import modin.pandas as pd
import utils
setattr(utils, 'pd', pd)