Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable's value lost between function calls in python

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")
like image 435
shuaiyuancn Avatar asked Jul 17 '26 16:07

shuaiyuancn


1 Answers

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]
like image 64
Sukrit Kalra Avatar answered Jul 20 '26 04:07

Sukrit Kalra



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!