0

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?

Anne Aunyme
  • 506
  • 4
  • 14
  • Have you considered [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-nonlocal-stmt)? – PM 77-1 May 16 '21 at 13:29
  • The error is due to the nested functions `increase_counter()` and `decrease_counter()` , you could increase and decrease the counters directly in the `if` statement and the code would work. if i=="+": counter += 1 elif i=="-": counter -+ 1 – Shivam Roy May 16 '21 at 13:36

0 Answers0