python interactive mode module import issue
Posted
by
Jeff
on Stack Overflow
See other posts from Stack Overflow
or by Jeff
Published on 2010-12-27T17:49:06Z
Indexed on
2010/12/27
17:54 UTC
Read the original article
Hit count: 191
I believe I have what would be called a scope issue, perhaps name space. Not too sure I'm new to python.
I'm trying to make a module that will search through a list using regular expressions. I'm sure there is a better way of doing it but this error that I'm getting is bugging me and I want to understand why.
here's my code:
class relist(list):
def __init__(self, l):
list.__init__(self, l)
def __getitem__(self, rexp):
r = re.compile(rexp)
res = filter(r.match, self)
return res
if __name__ == '__main__':
import re
listl = [x+y for x in 'test string' for y in 'another string for testing']
print(listl)
test = relist(listl)
print('----------------------------------')
print(test['[s.]'])
When I run this code through the command line it works the way I expect it to; however when I run it through python interactive mode I get the error
>>> test['[s.]']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "relist.py", line 8, in __getitem__
r = re.compile(rexp)
NameError: global name 're' is not defined
While in the interactive mode I do import re and I am able to use the re functions, but for some reason when I'm trying to execute the module it doesn't work.
Do I need to import re into the scope of the class? I wouldn't think so because doesn't python search through other scopes if it's not found in the current one?
I appreciate your help, and if there is a better way of doing this search I would be interested in knowing. Thanks
© Stack Overflow or respective owner