When declaring a constant that is only used one function, should that variable be declared locally since it is only used by that function, or globally since it is never going to change?
IE which is better:
CONSTANT = (1, 3, 5, 8)
##SOME OTHER CODE HERE
def function1(arg):
if arg in CONSTANT:
do something
or:
def function1(arg):
CONSTANT = (1, 3, 5, 8)
if arg in CONSTANT:
do something
I know there isn't a lot of difference between these two, but I just wanted to know which of the two practices is preferred since I'm just starting out and want to form good habits.
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.
The use of global variable in python is considered bad practice and should generally be avoided. Instead the user can try and use a parameter for passing a value onto a function or return a value to obtain it.
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.
I would keep it local. You can always just move it global in the future if you need to, or share it between functions by making them methods in a class and turning the constant into a class variable. In these situations, generally speaking, the more local, the better, and best is to hide implementation information within your functions, as in your second example. It doesn't make a huge difference here, but as your projects get bigger, maintainability and modularity will be sustained.
I would put them global because:
However, if you move to Object Oriented Programming, then I would put the constants as class variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With