Globals in general are a bad idea since they produce implicit assignations. Instead, is better to use return
to explicitly update the values.
If you want the function to take arguments created outside it, you can input them as arguments, e.g.:
indexer = 0
maybe = 1
def test(indexer, threshold):
if indexer < threshold:
indexer = threshold
return indexer # outside, so it'll always return
indexer = test(indexer=indexer, threshold=maybe)
indexer #1
If it really makes sense to you to think on indexer
and maybe
as defining the state of the program, and you prefer to modify them implicitly, you can still do
indexer = 0
maybe = 1
def test():
global indexer, maybe
if indexer < maybe:
indexer = maybe
test()
indexer # 1
A note on variables not defined in the local space
This is a simplified and corrected version of your program:
indexer = 0
maybe = 1
def test():
if indexer < maybe:
indexer = maybe
That produces local variable 'indexer' referenced before assignment
.
However, if I make this change:
indexer = 0
maybe = 1
def test():
if indexer < maybe:
foo = maybe # Change here!!!
there's no error!
that's because when Python finds variables inside the function declaration that were not declared in it's body (like foo
in the example), it's going to look for them in an outer namespace (the global space in this case). In your code you were lucky enough that, because you declared indexer = maybe
inside the body, the compiler assumed you wanted to use that declaration and not the one from the global and raised an error. Lucky enough... because this could be a source for many semantic errors. So, it's better to explicitly declare where the names are coming from instead of waiting for python to look for them in ways that may surprise us later when we want to change our program.