Weird import behavior
duncan.booth at invalid.invalid
Tue Oct 25 21:51:58 CEST 2005
> thanks for your quick reply. I guess I should have included the output.
> I thought I was clear in the error description.
> The problem is that I never assign to 'string'. I only reference it (as
> the error message correctly states). If you comment out the import
> statement in the except clause the program runs fine. Now notice that
> the exception hander never gets executed! Any explanation?
You have an assignment to 'string' in the function (import, class and def
statements are all equivalent to assignment statements so far as scoping
is concerned). It doesn't matter whether or not the assignment gets
executed: the compiler flags the variable as a local variable.
See the Python FAQ, 1.2.2:
1.2.2 What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a new value anywhere within
the function's body, it's assumed to be a local. If a variable is ever
assigned a new value inside the function, the variable is implicitly local,
and you need to explicitly declare it as 'global'.
More information about the Python-list