import in a class

Chris Rebert clp at
Wed Nov 26 18:49:25 CET 2008

On Wed, Nov 26, 2008 at 9:30 AM, TP <Tribulations at paralleles.invalid> wrote:
> Hi everybody,
> Here is a file "":
> ##########
> class a():
>   import re
>   def __init__( self ):
>      if "to", "toto" ):
> = "ok!"
>   def print_se( self ):
>      print
> a().print_se()
> ##########
> When python executes this file, we obtain an error:
> $ python
> [...]
> 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.

Follow the path of the Iguana...

> 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)
> --

More information about the Python-list mailing list