State variables in Python: when to choose classes, nonlocal variables, or function attributes

3.5k Views Asked by At

There are (at least) three different ways to track state information for functions in python (examples presented without any meaningful way to use the state information, obviously):

OOP Classes:

class foo:
    def __init__(self, start):
        self.state = start
    # whatever needs to be done with the state information

nonlocal variables (Python 3):

def foo(start):
    state = start
    def bar():
        nonlocal state
        # whatever needs to be done with the state information
    return bar

or function attributes:

def foo(start):
    def bar(bar.state):
        # whatever needs to be done with the state information
    bar.state = start
    return bar

I understand how each method works, but what I've not been able to reason is why (aside from familiarity) you would ever choose one method over another. Following the Zen of Python, classes would seem to be the most elegant technique, as it removes the need to nest function definitions. However, at the same time, classes might introduce more complexity than is needed.

What should one be considering when weighing which method to use in a program?

0

There are 0 best solutions below