classification
Title: error in variable
Type: Stage: resolved
Components: Windows Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Mahdi Jafary, paul.moore, steve.dower, tim.golden, xtreak, zach.ware
Priority: normal Keywords:

Created on 2019-06-11 15:26 by Mahdi Jafary, last changed 2019-06-11 15:55 by steve.dower. This issue is now closed.

Messages (3)
msg345238 - (view) Author: Mahdi Jafary (Mahdi Jafary) Date: 2019-06-11 15:26
this code is ok
def test(t):
	n = 0
	def f(t):
		print(t+str(N))
	f(t)	
test('test')
but this code have error

def test(t):
	n = 0
	def f(t):
		n = n+1
		print(t+str(n))
	f(t)	
test('test')	

we can fix this by edit code to:

def test(t):
	n = 0
	def f(t):
		N = n+1
		print(t+str(N))
	f(t)	
test('test')
msg345244 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-06-11 15:47
This tracker is for issues related to CPython. The examples presented in the report look more like user error with variables where N is not defined in the first examples. Can you please illustrate over the examples over how this is an issue with interpreter and the changes you are proposing?
msg345246 - (view) Author: Steve Dower (steve.dower) * (Python committer) Date: 2019-06-11 15:55
This is intended behavior.

When a variable has an assignment anywhere in a function, it becomes a local. Once a local variable exists, it will shadow the non-local variable.

So by having the "n =", you are marking "n" as a local variable. When the "n + 1" tries to read the local, it has not yet been set, so it fails.

If you want to read and write to "n" in the outer function, you will need the nonlocal statement - https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
History
Date User Action Args
2019-06-11 15:55:10steve.dowersetstatus: open -> closed
resolution: not a bug
messages: + msg345246

stage: resolved
2019-06-11 15:47:08xtreaksetnosy: + xtreak
messages: + msg345244
2019-06-11 15:26:26Mahdi Jafarycreate