import reassignment different at module and function scope
Chris Rebert
clp2 at rebertia.com
Sat Jan 31 02:47:23 EST 2009
On Fri, Jan 30, 2009 at 11:31 PM, Brendan Miller <catphive at catphive.net> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> If I:
>
> import sys
>
> sys = sys.version
>
> This executes find but:
>
> import sys
>
> def f():
> sys = sys.version
>
> This gives an error indicating that the sys on the right hand side of =
> is undefined. What gives?
More specifically, you get:
UnboundLocalError: local variable 'sys' referenced before assignment
Here's what's happening (IIRC):
Python sees (during "compilation") an assignment to 'sys' within the
function and (since there's no 'global' declaration within the
function) infers that the name 'sys', within the scope of the
function, *always* refers a local variable. IIRC, it does this for
significant optimization purposes.
However, when the function gets run and it goes to evaluate the
right-side of the assignment, it tries to lookup 'sys' as a local
variable, which obviously fails since it was never previously assigned
a value in the scope of the function, hence the error.
You can fix this by either renaming 'sys' within the function to something else:
def f():
version = sys.version #now sys is no longer treated as local
or you can indicate that you want to refer to the global sys variable:
def f():
global sys #tell python we mean the global sys
sys = sys.version #this will rebind 'sys' in the outer, global scope
Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
More information about the Python-list
mailing list