Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading