+ 3

How can I reassing a global variables in local namespaces in Python?

I have a problem of not being able to reassing global variables in local namespaces. For example you can't change global x's value in example: global x x = 5 def f(): x = 10 I thought I could have fixed that by: global x x = 5 def f(): nonlocal x x = 10 But it results in syntax errors. Is there a correct way to fix that problem?

30th Mar 2019, 7:45 PM
Seb TheS
Seb TheS - avatar
5 Réponses
+ 7
Seb TheS apologizes, I didn't know that and thank you for letting me know. And I just read about nonlocal variable, it says: Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope. And a change in nonlocal variable changes the value of local variable.
30th Mar 2019, 8:21 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 3
Yes syntax error 'cause there's no keyword called nonlocal in Python, lol. In the first code, in the function's scope, it cannot find that x is a global variable but it sees x as a local variable within the function with a value of 10. And hence upon printing x outside the function, it'll have a value of 5 and not 10. You must declare x as global inside the function. def f(): global x x=10
30th Mar 2019, 8:08 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 2
Seb TheS The nonlocal keyword allows to assign to variables in an outer scope, but not a global scope. So you can't use nonlocal in your function because then it would try to assign to a global scope. That's why you have got a SyntaxError. You can use nonlocal in a nested function only To change the global variable write global x inside the function: x = 5 def f(): global x x = 10 print(x) #5 f() print(x) #10
30th Mar 2019, 8:37 PM
portpass
+ 1
M. Watney Actually that works, but help("keywords") says that "nonlocal" is a keyword in Python, so I thought it would have some meaning within the problem. Local and Global (and __builtins__) were already quite clear.
30th Mar 2019, 8:14 PM
Seb TheS
Seb TheS - avatar
0
You need to declare global variable inside funtion: x = 5 def f(): global x x = 10
12th Apr 2019, 1:13 PM
Ridjeik
Ridjeik - avatar