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

UnboundLocalError in nested functions

I use the following code to experiment with nonlocal

def a():
    b = 5
    print(f"b (1) = {b}")
    def c():
        #nonlocal b
        print(f"b (2) = {b}")
        b = 3
    c()

a()

When I comment out nonlocal I get the following error:

Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "<string>", line 8, in a
  File "<string>", line 6, in c
UnboundLocalError: cannot access local variable 'b' where it is not associated with a value

I expected the value of variable b from function a to be printed out on the console and then a locale variable of the same name would be created. But obviously when the function is parsed, it is noted that there is a local variable called b in the function c, but it is not yet assigned a value, as this is done at runtime.
Are my thoughts correct and are there sources where I can read more about this?

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 :

yup , you’re correct When you comment out the nonlocal statement, Python treats b as a local variable inside function c(). Therefore, trying to access it before assigning a value results in an UnboundLocalError.
If you want to modify the variable b defined in the outer scope within the inner function c(), you need to use the nonlocal keyword.

but you can also achieve your desired output without nonlocal, just by passing the variable b as an argument to the inner function c().his way, you’re providing the value of b to the inner function and avoiding the scope-related issues.

def a():
    b = 5
    print(f"b (1) = {b}")
    
    def c(b):  
        print(f"b (2) = {b}")
        b = 3
    
    c(b)  

a()
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