Search code examples
pythonpython-module

Python module does not recognize global alias


A package within the same directory as my project main has a module that needs to reference a "well-known" module, such as pandas. However, the module does not recognize pandas.

For reference, I am running python 3.7.3.

Here is the directory I have set up:

test/
    main.py
    package1/
        __init__.py
        module.py

Here is the file main.py:

import pandas as pd
from package1.module import my_series

print(my_series([1,2,3]))

while module.py contains

def my_series(list1):
    return(pd.Series(list1))

I expect the output to be the series associated with this list:

0    1
1    2
2    3

but instead, I get the error

Traceback (most recent call last):
  2 ||   File "main.py", line 5, in <module>
  3 ||     print(my_series([1,2,3]))
  4 ||   File "/Users/awray_mac/Documents/test/package1/module.py", line 2, in my_series
  5 ||     return(pd.Series(list1))
  6 || NameError: name 'pd' is not defined

What is going on here? What is the proper way to have a submodule like this reference the already imported pandas package from the main file?


Solution

  • You need to import pandas in package1/module.py as below:

    import pandas as pd