I am calling a function (read_param) which depends on the ‘re’ module, defined in a file (libfun.py) from a master script (master.py). When I do so I get a NameError:
NameError: global name 're' is not defined
I import the ‘re’ module in the master script, but it seems that the function in the module I import can’t use it. I’d prefer not to import ‘re’ from within the function itself, since that seems wasteful. Why is this happening?
(this is a minimal example, not my actual code):
libfun.py:
def read_param(paramname, paramfile):
# code here depends on re module, e.g. calling re.split()
master.py:
#!/usr/bin/env python2
import re
import libfun as lf
lf.read_param('parameter', 'filename')
You are looking at the issue backwards. Modules ought to be self-contained, and therefore they need to manage all their own dependencies.
Imagine if you had fifteen different scripts, all of which used
readparam(). It would make no sense to force each of those scripts toimport re, just to usereadparam(). You’d end up importing it fifteen times, and you’d need to read the documentation or the source file to even know that you had to import it.The proper way to do it is to
import reat the top oflibfun.py. You don’t need to import it inmaster.pyunless you userewithin the body ofmaster.pyitself.