简体   繁体   English

我的 python 模块看不到其他模块

[英]My python module does not see other modules

I have a folder with 2 files.我有一个包含 2 个文件的文件夹。

import_test.py
main.py. 

Here is content of import_test.py:这是 import_test.py 的内容:

def some_function():
        df = pd.DataFrame({'col_1': [1,2,3],
                       'col_2': [1,2,3]})
        return df

Here is content of main.py:以下是 main.py 的内容:

import import_test
import pandas as pd
import importlib
importlib.reload(import_test)

import_test.some_function()

When I execute import_test.some_function() , I get back the following error:当我执行import_test.some_function()时,我收到以下错误:

NameError: name 'pd' is not defined

I guess I can solve this problem by adding import pandas as pd in my import_test.py file, but this seems redundant to me, since main.py already has the import statement for pandas.我想我可以通过在我的import_test.py文件中添加import pandas as pd来解决这个问题,但这对我来说似乎是多余的,因为main.py已经有了 pandas 的导入语句。 Is there way to avoid the redundancy?有没有办法避免冗余?

You have to import modules where they are being used.您必须在使用它们的地方导入模块。 When you use the import keyword, whatever you import is being bound to the current module's global namespace.当您使用import关键字时,无论您导入什么,都将绑定到当前模块的全局命名空间。

So it's not really a matter of your modules being unable to see each other, more that you've imported pandas in the wrong location.所以这并不是你的模块无法相互看到的问题,更多的是你在错误的位置导入了熊猫。 You can remove the pandas import from your main module if you import it where it's being used.如果你在使用它的地方导入它,你可以从你的主模块中删除 pandas 导入。

For what it's worth, C.Nivs is correct in saying that the module loader will only load pandas once even if you import it multiple times, so redundancy isn't much of an issue in that regard.对于它的价值,C.Nivs 说模块加载器只会加载 pandas 一次是正确的,即使你多次导入它,所以冗余在这方面并不是什么大问题。

You can try passing pd into the function, and then supply pd to the function when calling it.您可以尝试将pd传递给函数,然后在调用函数时将pd提供给该函数。

import_test.py :导入测试.py

def some_function(pd):
        df = pd.DataFrame({'col_1': [1,2,3],
                       'col_2': [1,2,3]})
        return df

main.py主程序

import import_test
import pandas as pd
import importlib
importlib.reload(import_test)

import_test.some_function(pd)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM