user2025161
user2025161

Reputation: 103

Using one module inside another in Python

I am trying to make some code a bit more modular in Python and am running into one issue which I'm sure is straight forward but I can't seem to see what the problem is.

Suppose I have a script, say MyScript.py:

import pandas as pd
import myFunction as mF

data_frame = mF.data_imp()

print(data_frame)

where myFunction.py contains the following:

def data_imp():
    return pd.read_table('myFile.txt', header = None, names = ['column'])

Running MyScript.py in the command line yields the following error:

    Traceback (most recent call last):
      File "MyScript.py", line 5, in <module>
        data_frame = mF.data_imp()
      File "/Users/tomack/Documents/python/StackQpd/myFunction.py", line 2, in data_imp
        return pd.read_table('myFile.txt', header = None, names = ['column'])
    NameError: name 'pd' is not defined

Upvotes: 1

Views: 172

Answers (2)

rostamn739
rostamn739

Reputation: 421

Answers here are right, because your module indeed lacks myFunction import.

If stated more broad this question can also contain following: in case of circular import the only 2 remedies are:

  1. import pandas as pd , but not from pandas import something
  2. Use imports right there in functions you need in-placd

Upvotes: 0

Simbarashe Timothy Motsi
Simbarashe Timothy Motsi

Reputation: 1525

You need to import pandas in your function or script myFunction:

def data_imp():
    import pandas as pd
    return pd.read_table('myFile.txt', header = None, names = ['column'])

Upvotes: 3

Related Questions