**Question**

In Python, if I have a function with local variables and nested functions, I can assign these variables in the nested functions with the help of nonlocal:

```
def f():
    x = 0
    def _g():
        nonlocal x
        x = 1
    def _h():
        x = 2
    _g()
    _h()
    print(x)
f() # 1

```

My issue with this solution is that if I have many local variables in f(), the use of nonlocal is verbose, and more disturbingly, it is very easy to forget nonlocal for a variable, and to create local variables in the nested functions without noticing it (what did I really mean in the h() function above, for instance?).

I have seen and used an alternative:

```
def f():
    class state:
        x = 0
    def _g():
        state.x = 1
    def _h():
        x = 2
    _g()
    _h()
    print(state.x)
f() # 1

```

If uses the fact that a class in Python is actually an object too. Using 'class' that way is actually the least verbose way of creating a mutable container for local values (I believe).

I think there are two questionable aspects in this pattern:

* That particular use of the 'class'-keyword might be considered as a hack.
* Since the container is somewhat artificial, it is sometimes difficult to find a good name for it (I went so far as testing the use of the name 'self' for it, but that seemed even more like a hack).

Is this a good pattern? What alternatives do you usually use?

If StackOverflow is not the right forum for this question, please advise on a different forum that you think is better suited (I did read the FAQs, but what the correct forum is for this question not obvious to me).

Thanks in advance.

P.S.

For the sake of completeness, there is at least one more alternative, which feels even more like a hack:

```
class f:
    def __init__(self):
        self.x = 0
        self._g()
        self._h()
        print(self.x)
    def _g(self):
        self.x = 1
    def _h(self):
        x = 2
f() # 1

```

This works because in Python, class instantiation has the same syntax as a function call.

**Answer**

See the accepted answer below. For a discussion about a solution when the function needs to return a value see [there](https://codereview.stackexchange.com/a/179294/36066).