Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global name 're' is not defined

I am new to python and working on a map reduce problem with mincemeat. I am getting the following error while running the mincemeat script.

$python mincemeat.py -p changeme localhost
error: uncaptured python exception, closing channel <__main__.Client connected at 0x923fdcc> 
(<type 'exceptions.NameError'>:global name 're' is not defined
 [/usr/lib/python2.7/asyncore.py|read|79]
 [/usr/lib/python2.7/asyncore.py|handle_read_event|438] 
 [/usr/lib/python2.7/asynchat.py|handle_read|140]
 [mincemeat.py|found_terminator|96]
 [mincemeat.py|process_command|194]
 [mincemeat.py|call_mapfn|170]
 [raw1.py|mapfn|43])

My code rests in raw1.py script which is given in the above stacktrace as [raw1.py|mapfn|43].

import re
import mincemeat

# ...

allStopWords = {'about':1, 'above':1, 'after':1, 'again':1}

def mapfn(fname, fcont):
    # ...
    for item in tList[1].split():
        word = re.sub(r'[^\w]', ' ', item).lower().strip()        # ERROR
        if (word not in allStopWords) and (len(word) > 1):
            # ....

I have already imported re in raw1.py. The error doesn't appear if I import re in mincemeat.py.

like image 343
Satyajit Singh Avatar asked Oct 04 '12 10:10

Satyajit Singh


2 Answers

You need to have the import statement in mapfn itself. mapfn gets executed in a different python process, so it doesn't have access to the original context (including imports) in which it was declared.

like image 122
Michael Fairley Avatar answered Sep 21 '22 14:09

Michael Fairley


"Global" variables in python are actually scoped to the module/file they're bound in; you do need to import them in every file that uses them.

A module name is just a variable like anything else.

like image 21
Wooble Avatar answered Sep 22 '22 14:09

Wooble