Can you explain closures (as they relate to Python)?

Technology CommunityCategory: PythonCan you explain closures (as they relate to Python)?
VietMX Staff asked 3 years ago

Objects are data with methods attached, closures are functions with data attached. The method of binding data to a function without actually passing them as parameters is called closure.

def make_counter():
    i = 0
    def counter(): # counter() is a closure
        nonlocal i
        i += 1
        return i
    return counter

c1 = make_counter()
c2 = make_counter()

print (c1(), c1(), c2(), c2())
# -> 1 2 1 2