0

Consider this example:

def func1():
    val = 1
    res = [1]
    def fun2():
        print(res)
        print(val)
        val = 2 
    fun2()
    print(val)

func1()

It raises the following exception:

UnboundLocalError: local variable 'val' referenced before assignment

List res can be accessed by fun2, but val cannot. I know list is mutable and int is not, but is there a way to make val accessible by fun2 as well? In a class, I could easily achieve that with self.val, but is there a way to do it inside a function?

john-hen
  • 4,410
  • 2
  • 23
  • 40
Pythoner
  • 5,265
  • 5
  • 33
  • 49

2 Answers2

1

Use the nonlocal statement to make a variable defined in an enclosing function accesible inside the inner function, like so:

def func1():
    val = 1
    res = [1]
    def fun2():
        nonlocal val
        print(res)
        print(val)
        val = 2 
    fun2()
    print(val)

func1()

See also: earlier SO question.

john-hen
  • 4,410
  • 2
  • 23
  • 40
0

You can do it in the following way:

def func1():
    val = 1
    res = [1]
    def fun2(val=val, res=res):
        print(res)
        print(val)
        val = 2 
        return val
    val = fun2()
    print(val)

Output is then

>>> func1()
[1]
1
2
WiseDev
  • 524
  • 4
  • 17