Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and reassign a global dictionary within a function

I have run into a bug in my Python code that seems very strange to me, and I now feel confused about how global dictionaries work.

My sample code:

myDict={'two':2,'three':3}

def f():    
    print myDict        
f()

Provides the output I expect: {'two': 2, 'three': 3}

However, if I change the code with one single line:

myDict={'two':2,'three':3}

def f():    
    print myDict        
    myDict={}
f()

then I get

 Traceback (most recent call last):
  File "test.py", line 9, in <module>
    f()
  File "proba.py", line 7, in f
    print myDict        
UnboundLocalError: local variable 'myDict' referenced before assignment

My questions:

  1. If I can print the global myDict in function f, why can't I reassign it?
  2. How can the line myDict={} break the print command, despite that it is executed later?

I'm using Python 2.7. Thank you for your help!

like image 239
leeladam Avatar asked Feb 07 '26 21:02

leeladam


1 Answers

1. If I can print the global myDict in function f, why can't I reassign it?

To assign to a global variable from a function you need to use a global directive. Otherwise Python will create a local variable with the same name instead.

global myDict

Add that to the top of the function.

2. How can the line myDict={} break the print command, despite that it is executed later?

Before it is ever executed, Python analyzes the entire function body to figure out what variables are local and which are global. Adding the assignment changes Python's analysis. It changes myDict from a global to a local variable.

This affects the print statement. Instead of printing the global myDict it prints a local variable. And at the point of printing the variable doesn't yet exist, thus the error.

like image 174
John Kugelman Avatar answered Feb 09 '26 12:02

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!