import in a class

Chris Rebert clp at rebertia.com
Wed Nov 26 12:49:25 EST 2008


On Wed, Nov 26, 2008 at 9:30 AM, TP <Tribulations at paralleles.invalid> wrote:
> 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):
>>> class Foo(object):
...     A=1
...     def foo(self): print A
...
>>> Foo().foo()
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)
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list