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: Scoping of variables in closures
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: bitfort, r.david.murray
Priority: normal Keywords:

Created on 2009-08-25 15:29 by bitfort, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg91954 - (view) Author: victor (bitfort) Date: 2009-08-25 15:29
I can't tell if this is "feature" or a "bug" but either way this
behavior struck me as strange.
"""
def func():
  x = 5
  def inc():
    temp = x + 1 # when inc() is execute, this line fails
    x = temp
    return x
  return inc

i = func()
i() # will raise error
"""
It says that x referenced before defined (when computing x + 1). It
seems that the fact that x is assigned in the local inc() that it
shadows the outer x.
Even stranger is that if you remove the the assignment of "x = temp"
there is no error; suggesting the assignment to x anywhere in the inner
function shadows the entire function. 

This is not the expected behavior, so I thought it may be bug.
msg91955 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2009-08-25 15:44
It's feature.

In python 3 you can use the 'nonlocal' keyword to access the variable in
the outer scope for assignment.
History
Date User Action Args
2022-04-11 14:56:52adminsetgithub: 51031
2009-08-25 16:40:27benjamin.petersonsetstatus: open -> closed
2009-08-25 15:44:45r.david.murraysetpriority: normal

nosy: + r.david.murray
messages: + msg91955

resolution: not a bug
stage: resolved
2009-08-25 15:29:10bitfortcreate