This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: scope resolving error
Type: behavior Stage:
Components: Versions: Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mark.dickinson, vpodpecan
Priority: normal Keywords:

Created on 2009-04-15 15:10 by vpodpecan, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg85992 - (view) Author: vid podpecan (vpodpecan) Date: 2009-04-15 15:10
Consider the following two functions:

def outer():
    a = 1
    def inner():
        print a
    
    inner()
#end outer()


def outer_BUG():
    a = 1
    def inner():
        print a
        a = 2
    
    inner()
#end outer_BUG()

The first function outer() works as expected (it prints 1), but the
second function ends with an UnboundLocalError, which says that the
"print a" statement inside inner() function references a variable before
assignment. Somehow, the interpreter gets to this conclusion by looking
at the next statement (a = 2) and forgets the already present variable a
from outer function.

This was observed with python 2.5.4 and older 2.5.2. Other releases were
not inspected.

Best regards,
Vid
msg85995 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2009-04-15 15:44
This is not a bug, just a common gotcha.  The rules are
described at:

http://docs.python.org/reference/executionmodel.html#naming

Here's the relevant excerpt:

"""If a name binding operation occurs anywhere within a code block, all 
uses of the name within the block are treated as references to the 
current block. This can lead to errors when a name is used within a 
block before it is bound. This rule is subtle. Python lacks declarations 
and allows name binding operations to occur anywhere within a code 
block. The local variables of a code block can be determined by scanning 
the entire text of the block for name binding operations."""
msg85996 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2009-04-15 15:45
Closing as invalid.
History
Date User Action Args
2022-04-11 14:56:47adminsetgithub: 50013
2009-04-15 15:45:40mark.dickinsonsetstatus: open -> closed
resolution: not a bug
messages: + msg85996
2009-04-15 15:44:43mark.dickinsonsetnosy: + mark.dickinson
messages: + msg85995
2009-04-15 15:10:45vpodpecancreate