1

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
3
  • 3
    use import pandas as pd inside myFunction module. Commented Feb 14, 2018 at 13:05
  • You should import pandas in your myFunction script Commented Feb 14, 2018 at 13:05
  • Thanks, so another question would be, suppose I had a set of python files - myFunction1.py, myFunction2.py, myFunction3.py - each containing functions that use 'read_table' from pandas and are called in MyScript.py, how can I minimise the number of times I type 'import pandas as pd'? Commented Feb 14, 2018 at 13:14

2 Answers 2

3

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.