Reputation: 5575
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)
Upvotes: 0
Views: 227
Reputation: 3574
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.
Upvotes: 1