简体   繁体   中英

My python module does not see other modules

I have a folder with 2 files.

import_test.py
main.py. 

Here is content of 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:

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:

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. 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.

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.

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.

You can try passing pd into the function, and then supply pd to the function when calling it.

import_test.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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