Search code examples
pythonhelperpython-module

Do helper files that I import, also need import statements?


I have a helper file which contains a function for plotting.

I also have my main notebook code, which uses the imports sns for seaborn, and plt for pyplot.

The helper file itself doesn't have an import statement to import these modules. In the notebook I am using it in, however, there are the following statements:

import seaborn as sns
import matplotlib.pyplot as plt

I import my helper file with the following line: from helpers.plotter import plots

And when I call the function I get the following error: NameError: name 'plt' is not defined

Do I need to have those import statements in the helper file? Is it not enough to have them in the notebook?


Solution

  • The import statement does two things:

    1. If necessary, it evaluates the contents of a .py file to define the module.
    2. It introduces a global variable in the current module to refer to the imported module.

    #1 may not happen, if, for example, the same module has already been imported. It's #2 that always happens, and the failure to do so that leads to the error your see.

    So yes, you need the import statement in your module.