[New-bugs-announce] [issue37568] Misleading UnBoundLocalError on assignment to closure variable

kolia report at bugs.python.org
Thu Jul 11 15:34:49 EDT 2019


New submission from kolia <kolia.sadeghi at gmail.com>:

def outer(a):   
    def inner():
      print(a)  
      a = 43    
    return inner
                
t = outer(42)   
                
print(t())      


Outputs:

~/Documents/repro.py in inner()                                   
      1 def outer(a):                                             
      2     def inner():                                          
----> 3       print(a)                                            
      4       a = 43                                              
      5     return inner                                          
                                                                  
UnboundLocalError: local variable 'a' referenced before assignment


This is misleading, since `a` is actually in scope on line 3. What is making it fail is the assignment on line 4, since `a` has not been declared `nonlocal`.

Instead, the error should point to line 4 and report an illegal assignment to a read-only closure variable.

----------
components: Interpreter Core
messages: 347703
nosy: kolia
priority: normal
severity: normal
status: open
title: Misleading UnBoundLocalError on assignment to closure variable
type: compile error
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37568>
_______________________________________


More information about the New-bugs-announce mailing list