Python : How to assign new value from outside of the function but the value is inside a function

Question:

Why val can’t access inside bar after declare new val’s value inside bar?

def foo() -> None:
        val = 'not change yet'
        def bar() -> None:
            print(val)        # Error: local variable 'val' referenced before assignment
            val = 'changed'
            print(val)
        bar()
foo()

How can I overcome the issue?
PS: I don’t want to put val outside foo.

Asked By: Zigatronz

||

Answers:

You should define val as nonlocal.

def foo() -> None:
        val = 'not change yet'
        def bar() -> None:
            nonlocal val
            print(val)        # Error: local variable 'val' referenced before assignment
            val = 'changed'
            print(val)
        bar()
foo()

Take a look here: W3Schools

Answered By: alanturing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.