Advertisement
Tritonio

Python nonlocal statement

Mar 17th, 2021
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1.  
  2.  
  3. Compare this, without using nonlocal:
  4.  
  5. x = 0
  6. def outer():
  7. x = 1
  8. def inner():
  9. x = 2
  10. print("inner:", x)
  11.  
  12. inner()
  13. print("outer:", x)
  14.  
  15. outer()
  16. print("global:", x)
  17.  
  18. # inner: 2
  19. # outer: 1
  20. # global: 0
  21.  
  22. To this, using nonlocal, where inner()'s x is now also outer()'s x:
  23.  
  24. x = 0
  25. def outer():
  26. x = 1
  27. def inner():
  28. nonlocal x
  29. x = 2
  30. print("inner:", x)
  31.  
  32. inner()
  33. print("outer:", x)
  34.  
  35. outer()
  36. print("global:", x)
  37.  
  38. # inner: 2
  39. # outer: 2
  40. # global: 0
  41.  
  42. If we were to use global, it would bind x to the properly "global" value:
  43.  
  44. x = 0
  45. def outer():
  46. x = 1
  47. def inner():
  48. global x
  49. x = 2
  50. print("inner:", x)
  51.  
  52. inner()
  53. print("outer:", x)
  54.  
  55. outer()
  56. print("global:", x)
  57.  
  58. # inner: 2
  59. # outer: 1
  60. # global: 2
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement