0

Within my function I want to increment various counts which are established outside of the function. These are count for different scenarios (e.g. count of successful completions, and various forms of errors). In total I have about 10 different counts i use.

While Python allows e.g. appending values to lists which were established outside of the function (e.g. list.append(new_running_count), trying to increment a number with the following code running_count = running_count + 1 throws up the error "local variable running_count referenced before assignment".

What is the most python way of dealing with this? Are global variables / passing the integers into the function the only way of doing it? (i am reluctant to do either, since passing and then returning 10 counts into the function would be clumberson, and also want to avoid global variables)

kyrenia
  • 5,431
  • 9
  • 63
  • 93
  • A good [explanation of Python's scoping rules](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) may be useful. – Celeo Apr 15 '15 at 22:24
  • 2
    Avoid using globals if possible. So passing as paramter is probably better. But we dont know for sure because we dont know what youre trying to do – Tim Apr 15 '15 at 22:25
  • *since passing 10 counts into the function is a bit annoying,* how does this work exactly? can we see some code? – Tim Apr 15 '15 at 22:29
  • This is what a class is for. – pzp Apr 15 '15 at 23:01

1 Answers1

1

Clearly, if you have ten counters, it is better to put them in a dictionary (or a list, but dictionaries have meaningful keys).

To use the dictionary in your function, the three usual solutions are global variable, argument or class variable. Argument is probably the clearer way.

Eric Levieil
  • 3,554
  • 2
  • 13
  • 18