0

As (nearly) any programmer else, also I'm a member of the 'No Global Variable' fan club, but in some cases I really don't know another, maybe also better way for solving a problem.

For example at the moment I'm programming a game in Pygame and I've got a mouse class which for example holds the actual mode, like select, aim or move. Of course I have to change that mode several times and also in several functions, so here is the problem, if the mouse-object isn't global, I really don't know how I could 'sync' the object in the different functions.

Maybe you could give me a hint how to solve that problem or if not you say 'I that case global variables are great full' anyway please say at least one of these two things :)

Leon

leon2225
  • 1
  • 1
  • 3
    Use a class and make it an attribute – Padraic Cunningham Jul 13 '15 at 21:04
  • One way to do this is to have the state you want modified passed into the functions that modify it. This makes it easy to see who modifies state where. – pvg Jul 13 '15 at 21:06
  • sometimes ugly choices are not too bad. Tradeoffs, pros/cons. – Pynchia Jul 13 '15 at 21:06
  • @PadraicCunningham Yep, that is what I've done, but in fact that is a kind of global variable, isn't it? – leon2225 Jul 13 '15 at 21:14
  • @leon2225, it is not the same as a global variable, you could change a global variable outside a function without even realising, with an attribute you must use the instance to access it so a lot harder to cause any bugs http://pastebin.com/HECzS7HM – Padraic Cunningham Jul 13 '15 at 21:29
  • @leon2225: No, global variable and instance attribute aren't definitely the same. Even if you are using that attribute in that same instance. And, well, this is Python, not C, so global variables aren't so big and bad things here. The risk of bugs is minimal because you are forced to use keyword "global" to change the var, and I believe that you are not stupid to forget how did you name it and confuse it with local variables. – Dalen Jul 13 '15 at 22:55
  • Maybe take a look at [this answer](https://stackoverflow.com/questions/31249852/copy-an-area-of-pixels/31262492#31262492) for another question to get an inspiration. There I use different classes for the different "mouse-modes", so I don't need a global variable (just a little wrapper class). – sloth Jul 14 '15 at 07:06

0 Answers0