2

Same code will work in JS, but in python it will not change variable, how do you change variables in nested functions? Thanks in advance and sorry for noob question

   def sample():
       a = False
       def sample2():
           a = True
       sample2()
       return a
  • 2
    `nonlocal a` in `sample2` – John Coleman Jun 06 '20 at 14:41
  • 1
    Consider redesign, so `nonlocal` is not necessary. The break of encapsulation makes maintenance difficult ... a problem I personally have with `js`. – Dr. V Jun 06 '20 at 14:45
  • To be fair, it's not possible to know it's a duplicate before you know the answer to this question. It's as if one asks: "*What is 6x7*", and somebody says: "*Duplicate, here is already a post about 42!*" – Dr. V Jun 06 '20 at 14:55

3 Answers3

3

Use nonlocal to modify variables outside the scope of the function.

   def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a
paltaa
  • 2,985
  • 13
  • 28
2

use nonlocal

def sample():
    a = False
    def sample2():
        nonlocal a
        a = True
    sample2()
    return a

Python 3 docs

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

imbr
  • 6,226
  • 4
  • 53
  • 65
2
 def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a

This should work.