# Problem: global state makes code hard to test and debug
counter = 0defbad_increment():
global counter
counter += 1return counter
# Better: use a classclassCounter:
def__init__(self):
self.value = 0defincrement(self):
self.value += 1return self.value
c = Counter()
print(c.increment())
print(c.increment())
print(c.increment())
# Or use a closuredefmake_counter():
count = 0defincrement():
nonlocal count
count += 1return count
return increment
inc = make_counter()
print(inc())
print(inc())
Output
Click "Run" to execute your code
Classes and closures are almost always better than global variables. They allow multiple independent instances and are easier to test.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?