My python module does not see other modules

Question:

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?

Asked By: user1700890

||

Answers:

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)
Answered By: Tega Rorobi

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.

Answered By: Tempystral
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.