Search code examples
pythonglobal-variables

Globals between files in python


I am making a game, a simple 2d RPG in python, using pygame. I'm now adding zooming in and out using the scrollwheel. I have a file called stuff.py along with my main.py file and a bunch of other files (player.py, enemy1.py, enemySpawner.py, chest.py etc.). In the stuff.py file, I have an int called sizeofEverything, and everything is scaled ( square shape) to sizeofEverything. Main.py is the only file that is executed, so In main.py, I detect if the scrollWheel has been interacted with, and if it has been, I want to change sizeofEverything. The problem is, that would just change the local copy of sizeofEverything that I imported into main.py .I need some way to change it, from the main.py file, so that it also updates in all the other files (enemy1.py, player.py etc. ) How would this be done?


Solution

  • I'd recommend rethinking how the variables are defined and how you change them. For example, instead of trying to change a variable in another file, perhaps you can pass a variable to a function in another file, and store all the variables in the main script. Global variables tend to be frowned upon, but only because they make things pretty messy overall.