1

So I am making a small game using Pygame just to get some experience. For this example, we'll just say I have two files(a.py and b.py). In a.py I have a variable called 'score'. I to be able to change the value of score from both a.py and b.py. I know to access score from my class in b.py I would simply need to put in the line

import a

at the start of b.py. The problem I'm having is that a.py imports a class from b.py. So a imports b which imports a. Obviously that doesn't work. My work-around to this was to create a separate file(let's say c.py) and keep the score variable in there. Then a will import b and c, b will just import c, and all is well. This seems like bad practice though, and I feel like there must be some other way to do this, though I haven't found one. So my question is a) Is this considered a 'wrong' way to do this? and b) Is there a better way?

  • The third module is a good way to handle the problem. I would have no problem doing that. – tdelaney Apr 15 '18 at 00:25
  • 1
    You should instead pass the instance of each class to the instance of the other class. Then you don’t have to mess with a clunky solution like sharing module-global variables between modules. – robobrobro Apr 15 '18 at 00:25
  • you can just import classes or modules using `from a import score` – johnashu Apr 15 '18 at 00:27
  • 1
    @robobrobro - how exactly?Multiple instances of some class, functions in each module that just have the same circular import problem? Not for me! – tdelaney Apr 15 '18 at 00:27
  • A different use case is multiple modules sharing a configuration. You'd implement one `config.py` that knows how to get the config from disk and everyone uses it. Your three module solution is common and normal. A module is just a namespace you stick stuff in. No need to make it complicated! – tdelaney Apr 15 '18 at 00:29

0 Answers0