Unexpected python exception

Richard Purdie rpurdie at rpsys.net
Wed Nov 11 13:37:04 CET 2009


On Wed, 2009-11-11 at 12:21 +0100, Diez B. Roggisch wrote:
> As the import-statement in a function/method-scope doesn't leak the 
> imported names into the module scope, python treats them as locals. 
> Which makes your code equivalent to
> 
> 
> x = 1000
> 
> def foo():
>      print x
>      x = 10

Aha, thanks. This makes it clear whats happening.

> Throws the same error. The remedy is to inform python that a specific 
> name belongs to global scope, using the "global"-statement.
> 
> def foo():
>      global x
>      print x
>      x = 10
> 
> 
> Beware though that then of course *assigning* to x is on global level. 
> This shouldn't be of any difference in your case though, because of the 
> import-only-once-mechanics of python.

Is there a way to make the "global x" apply to all functions without
adding it to each one? 

I suspect this equates to intentionally "leaking the imported names into
the module scope"? :)

What I'm trying to do is to avoid having "import X" statements
everywhere by changing __builtin__. It seems my approach doesn't have
quite the same effect as a true import though.

Cheers,

Richard




More information about the Python-list mailing list