0

Global variables in Python

Fellas, I was trying to debug a Python code that involves ten different functions, and one message given by Pycharm was: "X should be a global variable." I kinda understand the concept behind global variables: they are declared outside of any function and operate throughout the code; but is it a good idea using a lot of global variables? (This is the first question) According to some stuff I've read in foruns, they can affect the functionaly of the program in unexpected ways, though I have no clue how. So, the second question is: is it using global variables part of "good practice" or is better the avoid them? thx in advance.

8th Jan 2025, 3:04 PM
FV Silva
FV Silva - avatar
3 Answers
+ 3
My opinion: If you plan on being able to debug your code, don't use global variables. it is definitely not good practice. Some people have different opinions on it. I find it useful to quickly test something, but building your code using global variables can break so much. The only "globals" i would use is constants in something like constants.py. I then just import that into different files as i need to update some stuff "globally". Examples would be enemy density, item spawn density, message screen height, viewport scroll buffer zone etc the above constants aren't modified during runtime so they aren't changed in unintended or hidden ways like global variables. in general, explicit > implicit when it comes to coding. and... i cringe (again, my opinion) when i see global variables as I've caused havoc using them, having to refactor immensely to get things back in a working state
8th Jan 2025, 6:08 PM
PietPadda
PietPadda - avatar
+ 2
Thanks a lot, pal
8th Jan 2025, 7:15 PM
FV Silva
FV Silva - avatar
+ 1
If it's just one file and relatively simple code and it makes things simpler, use global variable. It will not kill you... But it's also not that hard to rewrite the code and pass X as a function argument..
9th Jan 2025, 7:44 AM
Bob_Li
Bob_Li - avatar