Python closure with side-effects

Viewed 676

I'm wondering if it's possible for a closure in Python to manipulate variables in its namespace. You might call this side-effects because the state is being changed outside the closure itself. I'd like to do something like this

def closureMaker():
  x = 0
  def closure():
    x+=1
    print x
  return closure

a = closureMaker()
a()
1
a()
2

Obviously what I hope to do is more complicated, but this example illustrates what I'm talking about.

2 Answers
Related