Question: I'm new to programming, and have recently learned python and the basics of object oriented programming. I'm aware that having lots of global variables is generally a bad idea, and that I can put them all into a class instead. Is this the right way to do it?

```
class GameState(object):
    def __init__(self):
        self.variable1 = 1
        self.variable2 = 2
        self.list = [3, 4, 5]

g_state = GameState()

```

And, if I wish to access the variables within g\_state, what is the best way to go about doing it?

Pass g\_state into the functions/classes that need access?
Implement getters and call those?
Use g\_state.variable1 directly?

Or is there a better way?

EDIT: To be more specific, I'm trying to write a game in python using pygame, and was thinking of putting my gamestate variables into a class so as to not have a bunch of global variables lying around. I'm unsure of how to access those variables with good design so I don't run into trouble later.

Answer: 
You are right that too many global variables is not a good idea. Polluted global namespace may lead to errors.

However, **don't put them into class for the sake of it**. If you have really that many variables maybe you should consider splitting your program into multiple modules.

Also please understand that you can't really crate global variables in Python like you can in JavaScript. Your variables are always scoped under the module.

Let me illustrate with an example. Module a.py:

```
A = 42

```

Module b.py:

```
import a

print(A)

```

What do you get? `NameError`. Why? because variable A is not global, it is under module `a`. You need to use `a.A` to reference it.

There is no need to stuff variables under class. They are under modules, which acts as a namespace, and there is **nothing wrong** with it.
There are two ways to access the variables: one global object or passing an instance to a function. The first one is a bad idea too in general. The second one is better. But do not create a single object with all variables! (see the first comment).

There are more things to consider if you pass around an object. A good idea is implementing things as a member-function if suitable.

```
class VariableBox(object):
    def __init__(self):
        self.variable1 = 1
        self.variable2 = 2
        self.list = [3, 4, 5]

    def do_something(self):
        self.variable1 = self.variable2 + 42
        return self.variable1

```