TomHere TomHere - 7 months ago 10
Python Question

Python: Understanding global a little bit more

I have a program in python. part of the program is:

suggestengines = get_suggestengines(suggestengines)
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)


For further programming I want to make a function of it:

def first_step():
suggestengines = get_suggestengines(suggestengines)
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)


Now I get an error for "suggestengines" that I want to pass into get_suggestengines(). Also sleep timer and seeds get a marker, that I don't use them in the rest of the program. I googled it and got the answer: Us global. So I added global for everything

def first_step():
global suggestengines
global sleeptimer
global seeds
suggestengines = get_suggestengines(suggestengines) #which engines to run?
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)


In further part of the program I have

for seed in tqdm(seeds, leave=True):


there the program gives me an error vor seeds in tqdm. If I change it to also make a def of it like:

def partTwo():
for seed in tqdm(seeds, leave=True):


Then I don't get an error anymore although I didn't used global. Can someone explain me why and if I need to use global in part 2 also?

Answer

The statement

global <identifier>

tells python that <identifier> should refer to a global when used in assignments. This is necessary in functions that change globals because Python has no syntactical difference between declaring a variable and assigning to an existing variable. The default in python is to have assignments in functions create new variables, rather than change global state.

When you just read from a variable there is no syntactic ambiguity, so Python will just use whatever variable it finds (i.e. global if there is no local one).

Example:

a = 1

def foo():
    a = 2 # this will create a new, local variable a

def bar():
    global a # "when I refer to a, I mean the global one"
    a = 2    # this will change the global variable a

If no global with the specified name exists, the global statement itself will not create a new global variable, but any following assignment will. E.g. given the following:

def x():
    global c

def y():
    global c
    c = 1

def z()
    print c

x(); z() would be an error(global name 'c' is not defined), while y(); z() would print 1.

Comments