2

I have a Python module with a few functions. At the moment, these functions are only called from main(), but I expect to import the module from other files in the future.

I have a counter variable that is used and modified by most of these functions. At the moment I am passing it around as a parameter, and returning it with every function call.

This works but seems silly. I considered including a constant variable COUNTER that is used directly by all functions. However, I assume that constants are not supposed to be modified.

Is there a cleaner approach than passing the counter variable back and forth?

unicorn_poet
  • 475
  • 1
  • 5
  • 14
  • 5
    I think the keyword you are looking for is `global` https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – Cory Kramer Jun 18 '15 at 17:32
  • 4
    One option would be creating a class and making `counter` an attribute. – bereal Jun 18 '15 at 17:34
  • 2
    Consider using a class attribute as stated above, it may seem silly to be passing the variable around like you are, but that is part of explicit coding. Globals in a very general sense are not a good idea, especially ones with common names like `counter` – MrAlexBailey Jun 18 '15 at 17:35

1 Answers1

2

Creating a class with counter as one of its attribute will be a good solution.

Since the current functions will be explicitly called in the future, making counter an attribute will save the callee of variable passing and you of probably additional error checking.

Also the counter variable can be abstracted from the callee function reducing errors. This point depends on your implementation though.

Obscure Geek
  • 749
  • 10
  • 22
  • So in general, is it preferable to encapsulate it all in a class than to use a couple of `global` variables? – unicorn_poet Jun 18 '15 at 18:12
  • It is actually an application specific rule not a generic one. In your scenario the class method was suited since you wish to use your functions elsewhere. An example for the global use might be your class reads a configuration file and creates a JSON object for the same. Now it may be better suited to a developer, who wishes to use your class, to create a global configuration object of your class and use it. – Obscure Geek Jun 18 '15 at 18:16