1

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')
andyras
  • 15,542
  • 6
  • 55
  • 77
  • 6
    Shouldn't you import `re` in the module where you actually use it? – Rohit Jain Nov 28 '12 at 17:16
  • Please show the full traceback and the code causing the error. You do not show any code relying on the variable `re`. – Marcin Nov 28 '12 at 17:17
  • " I'd prefer not to import 're' from within the function itself, since that seems wasteful." - you're making life difficult for yourself for no reason http://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times – YXD Nov 28 '12 at 17:17

1 Answers1

4

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 to import re, just to use readparam(). 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 re at the top of libfun.py. You don't need to import it in master.py unless you use re within the body of master.py itself.

PeterBB
  • 343
  • 2
  • 9
  • 1
    Also, it's worth noting that "globals" in Python are not really global, they are constrained to the module in which they're defined. Thus, importing `re` in `master.py` makes `re` available in `master.py` but does *absolutely nothing* to make `re` available in `libfun.py`. – kindall Nov 28 '12 at 17:39