This question already has an answer here:
What am I doing wrong here?
counter = 0
def increment():
counter += 1
increment()
The above code throws an UnboundLocalError
.
This question already has an answer here:
What am I doing wrong here?
counter = 0
def increment():
counter += 1
increment()
The above code throws an UnboundLocalError
.
try this
To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the
nonlocal
keyword to modify a closure variable.* The original question's title asked about closures in Python.