import in a class

T

TP

Hi everybody,

Here is a file "test_import_scope.py":
##########
class a():
import re
def __init__( self ):
if re.search( "to", "toto" ):
self.se = "ok!"
def print_se( self ):
print self.se
a().print_se()
##########

When python executes this file, we obtain an error:

$ python test_import_scope.py
[...]
NameError: global name 're' is not defined

Why?

When the re module is imported in the __init__ function or out of the class
(at the top of the file), it works obviously perfectly.

Thanks in advance,

Julien

--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
 
C

Chris Rebert

Hi everybody,

Here is a file "test_import_scope.py":
##########
class a():
import re
def __init__( self ):
if re.search( "to", "toto" ):
self.se = "ok!"
def print_se( self ):
print self.se
a().print_se()
##########

When python executes this file, we obtain an error:

$ python test_import_scope.py
[...]
NameError: global name 're' is not defined

Why?

Because Python doesn't look in class-scope when doing name resolution.
It checks the local [function] namespace, then any nested [function]
scopes (not applicable in this case), then the module/global
namespace, and finally the builtins namespace. The class' namespace
never comes into the equation.

Consider this simpler example (remember that `import` assigns a module
to its name in the importing scope):.... A=1
.... def foo(self): print A
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
NameError: global name 'A' is not defined

So in foo(), `A` can be accessed by Foo.A or self.A, but not just plain `A`.
I agree it's not entirely intuitive, but remember that Python != Java.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
When the re module is imported in the __init__ function or out of the class
(at the top of the file), it works obviously perfectly.

Thanks in advance,

Julien

--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,089
Latest member
Ketologenic

Latest Threads

Top