I’m making a game in Python, and I have an object to store all of the user’s preferences in, referred to as gameSettings
.
When running functions in a seperate file (functions.py
) I have to create a new local gameSettings
var in every single function in the file.
# functions.py def myFunc1(x, y, gameSettings): if gameSettings.printX == True: print(x) def myFunc2(z, gameSettings): if gameSettings.printZ == True: print(z) def myFunc3(a, b, gameSettings): if gameSettings.add == True: print(a+b) elif gameSettings.subtract == True: print(a-b) # (example code)
This also means I have to run the gameSettings
object through almost every function I’ve written so far.
I was wondering if there was a better way to do this, as I doubt this is very efficient. I can’t just import the gameSettings
object at launch (as that would cause a circular import), but even if I could the object’s variables can be modified by the user and my guess is that changing the gameSettings
object in main.py
will not change its functions.py
counterpart.
Advertisement
Answer
How do you see this solution? Using a shared dictionary. From my experience, I’d store that settings as a .json file and load it when you start the game.
main.py
from func1 import Func1 from func2 import Func2 class GameSettings(): def __init__(self, printX=False, printZ=False): self.settings = { 'printX': printX, 'printZ': printZ } settings = GameSettings(printX=True, printZ=False) func1 = Func1(settings) func1.myFunc1(1, 2) print(func1.settings.settings) settings.settings.update({'printX': False}) print(func1.settings.settings) func1.myFunc1(1, 2) func2 = Func2(settings) func2.myFunc2(3) settings.settings.update({'printZ': True}) func2.myFunc2(3)
func1.py
class Func1(): def __init__(self, settings=None): self.settings = settings def myFunc1(self, x, y): if self.settings.settings['printX'] == True: print(x)
func2.py
class Func2(): def __init__(self, settings=None): self.settings = settings def myFunc2(self, z): if self.settings.settings['printZ'] == True: print(z)
Here’s the output of executing this code
bash-5.1$ python3 main.py 1 {'printX': True, 'printZ': False} {'printX': False, 'printZ': False} 3