Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.

like image 291
knowncitizen Avatar asked Aug 17 '08 19:08

knowncitizen


People also ask

Why we use closures in Python?

Python closures help avoiding the usage of global values and provide some form of data hiding. They are used in Python decorators.

What are closures and decorators in Python?

A decorator is a function that takes in a function and returns an augmented copy of that function. When writing closures and decorators, you must keep the scope of each function in mind. In Python, functions define scope. Closures have access to the scope of the function that returns them; the decorator's scope.

What are closures used for?

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.

What are closures in programming?

A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.


2 Answers

Closure on closures

Objects are data with methods attached, closures are functions with data attached.

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 
like image 96
jfs Avatar answered Sep 20 '22 12:09

jfs


It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:

>>> def makeConstantAdder(x): ...     constant = x ...     def adder(y): ...         return y + constant ...     return adder ...  >>> f = makeConstantAdder(12) >>> f(3) 15 >>> g = makeConstantAdder(4) >>> g(3) 7 

Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.

like image 41
Anders Eurenius Avatar answered Sep 19 '22 12:09

Anders Eurenius