Consider the following (basically I start a count and each time there is a "+" I go up by 1 and each time there is a "-" I go down by 1):
def big_procedure(state0, instructions):
p = {"counter":state0}
def increase_counter():
p["counter"] +=1
def decrease_counter():
p["counter"] -=1
for i in instructions:
if i=="+": increase_counter()
elif i=="-": decrease_counter()
return p["counter"]
print(big_procedure(0, "++-"))
It works fine, however using a dict here just for one parameter (counter) is awkward. I would rather have something like:
def big_procedure(state0, instructions):
counter = state0
def increase_counter():
counter +=1
def decrease_counter():
counter -=1
for i in instructions:
if i=="+": increase_counter()
elif i=="-": decrease_counter()
return counter
print(big_procedure(0, "++-"))
Which doesn't work:
UnboundLocalError: local variable 'counter' referenced before assignment
I know there are way to make variables global, but I want to be sure counter is not modified by an other instance of big_procedure running at the same time. Is there a good way to do that or am I better sticking with the awkward dict?