Abhirath Mahipal Abhirath Mahipal - 5 months ago 14
Python Question

NameError after packaging Python code

I've been using IPython for sometime without ever having to package code. I glanced through the following pages and setup a directory structure for my modules and now use IPython to initiate the program.

https://docs.python.org/3/reference/import.html

https://docs.python.org/3/tutorial/modules.html

http://pythoncentral.io/how-to-create-a-python-package/

Here is a gist of my setup

root foder


  1. modules(directory)

    1.1 external.py

    1.2 getdata.py

  2. driver.ipynb



I created a directory called modules and created two files.

modules (directory)

-- external.py (contains the following)

import glob # and many other import statements


-- getdata.py (contains the following)

def funcname():
file_list = glob.glob("Data/")

def other_func():
x = x + 3


Now I run the following code in an IPython notebook

from modules import external
from modules.getdata import *
# so that I can funcname() instead of modules.getdata.funcname()

other_func() # runs as expected
funcname() # NameError global name 'glob' is not defined


Running glob.glob("Data/") in the IPython notebook does not give out any error.

How do I fix this namespace issue without renaming any function? I have a dozen functions and they all have the same issue.

Edit 1:- I forgot to mention stuff that I've already tried

import statement in getdata.py

import glob
def funcname():
file_list = glob.glob("Data/")

def other_func():
x = x + 3


I have more than one file which uses glob. Is there any better alternative other that importing modules in every file?

Answer

Add import glob in getdata.py (where the glob module is used), not in the external.py.

import glob  # <--

def funcname():
    file_list = glob.glob("Data/")

def other_func():
    x = x + 3