Global variable's value lost between function calls in python
list-comprehension, python, python-2.7
Solution
I think making it `global` would work. Any variable defined in the global scope which is to be edited should be specified as `global` in that function. Your code just makes a local variable `CACHE_KEYS` and stores the information correctly. But, to make sure that it is copied to the global variable, declare the variable as `global` in the function. You call the `append` function on `CACHE` and hence that works fine. Your code after the changes.
import bisect
import csv
DB_FILE = "GeoLiteCity-Location.csv"
# ['locId', 'country', 'region', 'city', 'postalCode', 'latitude', 'longitude', 'metroCode', 'areaCode']
CACHE = []
CACHE_KEYS = None
def load():
R = csv.reader(open(DB_FILE))
for line in R:
CACHE.append(line)
# sort by city
CACHE.sort(key=lambda x: x[3])
global CACHE_KEYS
CACHE_KEYS = [x[3] for x in CACHE]
if __name__ == "__main__":
load()
Anytime you assign a value to a global variable you have to declare it as `global`. See the following code snippet.
listOne = []
def load():
listOne+=[2]
if __name__=="__main__":
load()
The above code has an assignment and not an `append` call. This gives the following error.
UnboundLocalError: local variable 'listOne' referenced before assignment
But, executing the following snippet.
listOne = []
def load():
listOne.append(2)
if __name__=="__main__":
load()
gives the following output.
>>> print listOne
[2]
Problem
I know I must have missed something basic -- just want to make sure I get the precise answer. I have the following code. Why `CACHE_KEYS` is still None after `load()` while `CACHE` is not? ``` import bisect import csv DB_FILE = "GeoLiteCity-Location.csv" # ['locId', 'country', 'region', 'city', 'postalCode', 'latitude', 'longitude', 'metroCode', 'areaCode'] CACHE = [] CACHE_KEYS = None def load(): R = csv.reader(open(DB_FILE)) for line in R: CACHE.append(line) # sort by city CACHE.sort(key=lambda x: x[3]) CACHE_KEYS = [x[3] for x in CACHE] if __name__ == "__main__": load() # test # print get_geo("Ruther Glen") ```