Bob Smith Bob Smith - 1 year ago 69
Python Question

NameError -- imported modules when script is broken down in multiple python files

It is hard to find a title for this question and hopefully this thread is not a duplicate.

I was writing that long script in Python 2.7 (using PyCharm 2016.2.2) for a project and decided to split it in different .py files which I could then import into a main file.

Unfortunately, it seems that when importing a module (e.g. numpy) earlier in the code does not mean that the .py files that are imported below will have knowledge of that.

I am new to python and I was wondering whether there is an easy workaround for that one.

To be more clear, here is an example structure of my code: (the file that is used to run the script):

import basic
import load_data

import pandas
import numpy

raw_input = pandas.read_excel('April.xls', index_col = 'DateTime')

The second line of would cause an error "NameError: name 'numpy' is not defined", meaning the numpy that was imported in is not passed to the

I guess that a similar error would occur for the code in since 'pandas' would not be a defined name.

Any ideas?


Answer Source

The numpy module imported in has a reference defined only withing scope. You have to explictly import numpy everywhere you use it.

import numpy
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download