import in a class
clp at rebertia.com
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 "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
> When python executes this file, we obtain an error:
> $ python test_import_scope.py
> NameError: global name 're' is not defined
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):
... 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.
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,
> python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
> "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