<p>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.</p>

[{'answer_id': 13875, 'author': 'Anders Eurenius', 'author_id': 1421, 'author_profile': 'https://Stackoverflow.com/users/1421', 'pm_score': 6, 'selected': False, 'text': '<p>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:</p>\n\n<pre><code>&gt;&gt;&gt; def makeConstantAdder(x):\n...     constant = x\n...     def adder(y):\n...         return y + constant\n...     return adder\n... \n&gt;&gt;&gt; f = makeConstantAdder(12)\n&gt;&gt;&gt; f(3)\n15\n&gt;&gt;&gt; g = makeConstantAdder(4)\n&gt;&gt;&gt; g(3)\n7\n</code></pre>\n\n<p>Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.</p>\n'}, {'answer_id': 13902, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve never heard of transactions being used in the same context as explaining what a closure is and there really aren\'t any transaction semantics here.</p>\n\n<p>It\'s called a closure because it "closes over" the outside variable (constant)--i.e., it\'s not just a function but an enclosure of the environment where the function was created. </p>\n\n<p>In the following example, calling the closure g after changing x will also change the value of x within g, since g closes over x:</p>\n\n<pre><code>x = 0\n\ndef f():\n    def g(): \n        return x * 2\n    return g\n\n\nclosure = f()\nprint(closure()) # 0\nx = 2\nprint(closure()) # 4\n</code></pre>\n'}, {'answer_id': 13906, 'author': 'ESV', 'author_id': 150, 'author_profile': 'https://Stackoverflow.com/users/150', 'pm_score': 4, 'selected': False, 'text': '<p>I like <a href="http://effbot.org/zone/closure.htm" rel="noreferrer">this rough, succinct definition</a>:</p>\n\n<blockquote>\n  <p>A function that can refer to environments that are no longer active.</p>\n</blockquote>\n\n<p>I\'d add</p>\n\n<blockquote>\n  <p>A closure allows you to bind variables into a function <em>without passing them as parameters</em>.</p>\n</blockquote>\n\n<p>Decorators which accept parameters are a common use for closures.  Closures are a common implementation mechanism for that sort of "function factory".  I frequently choose to use closures in the <a href="http://c2.com/cgi/wiki?StrategyPattern" rel="noreferrer">Strategy Pattern</a> when the strategy is modified by data at run-time.</p>\n\n<p>In a language that allows anonymous block definition -- e.g., Ruby, C# -- closures can be used to implement (what amount to) novel new control structures.  The lack of anonymous blocks is among <a href="http://ivan.truemesh.com/archives/000411.html" rel="noreferrer">the limitations of closures in Python</a>.</p>\n'}, {'answer_id': 24061, 'author': 'Jegschemesch', 'author_id': 1586, 'author_profile': 'https://Stackoverflow.com/users/1586', 'pm_score': 4, 'selected': False, 'text': '<p>To be honest, I understand closures perfectly well except I\'ve never been clear about what exactly is the thing which is the "closure" and what\'s so "closure" about it. I recommend you give up looking for any logic behind the choice of term.</p>\n\n<p>Anyway, here\'s my explanation:</p>\n\n<pre><code>def foo():\n   x = 3\n   def bar():\n      print x\n   x = 5\n   return bar\n\nbar = foo()\nbar()   # print 5\n</code></pre>\n\n<p>A key idea here is that the function object returned from foo retains a hook to the local var \'x\' even though \'x\' has gone out of scope and should be defunct. This hook is to the var itself, not just the value that var had at the time, so when bar is called, it prints 5, not 3.</p>\n\n<p>Also be clear that Python 2.x has limited closure: there\'s no way I can modify \'x\' inside \'bar\' because writing \'x = bla\' would declare a local \'x\' in bar, not assign to \'x\' of foo. This is a side-effect of Python\'s assignment=declaration. To get around this, Python 3.0 introduces the nonlocal keyword:</p>\n\n<pre><code>def foo():\n   x = 3\n   def bar():\n      print x\n   def ack():\n      nonlocal x\n      x = 7\n   x = 5\n   return (bar, ack)\n\nbar, ack = foo()\nack()   # modify x of the call to foo\nbar()   # print 7\n</code></pre>\n'}, {'answer_id': 94543, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': -1, 'selected': False, 'text': "<p>The best explanation I ever saw of a closure was to explain the mechanism.  It went something like this:</p>\n\n<p>Imagine your program stack as a degenerate tree where each node has only one child and the single leaf node is the context of your currently executing procedure.</p>\n\n<p>Now relax the constraint that each node can have only one child.</p>\n\n<p>If you do this, you can have a construct ('yield') that can return from a procedure without discarding the local context (i.e. it doesn't pop it off the stack when you return).  The next time the procedure is invoked, the invocation picks up the old stack (tree) frame and continues executing where it left off.</p>\n"}, {'answer_id': 141426, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 8, 'selected': True, 'text': '<p><a href="http://mrevelle.blogspot.com/2006/10/closure-on-closures.html" rel="noreferrer">Closure on closures</a></p>\n\n<blockquote>\n  <p>Objects are data with methods\n  attached, closures are functions with\n  data attached.</p>\n</blockquote>\n\n<pre><code>def make_counter():\n    i = 0\n    def counter(): # counter() is a closure\n        nonlocal i\n        i += 1\n        return i\n    return counter\n\nc1 = make_counter()\nc2 = make_counter()\n\nprint (c1(), c1(), c2(), c2())\n# -&gt; 1 2 1 2\n</code></pre>\n'}, {'answer_id': 473491, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a typical use case for closures - callbacks for GUI elements (this would be an alternative to subclassing the button class). For example, you can construct a function that will be called in response to a button press, and "close" over the relevant variables in the parent scope that are necessary for processing the click. This way you can wire up pretty complicated interfaces from the same initialization function, building all the dependencies into the closure.</p>\n'}, {'answer_id': 18918261, 'author': 'Ricardo Avila', 'author_id': 2799405, 'author_profile': 'https://Stackoverflow.com/users/2799405', 'pm_score': 0, 'selected': False, 'text': '<p>For me, "closures" are functions which are capable to remember the environment they were created. This functionality, allows you to use variables or methods within the closure wich, in other way,you wouldn\'t be able to use either because they don\'t exist anymore or  they are out of reach due to scope. Let\'s look at this code in ruby:</p>\n\n<pre><code>def makefunction (x)\n  def multiply (a,b)\n    puts a*b\n  end\n  return lambda {|n| multiply(n,x)} # =&gt; returning a closure\nend\n\nfunc = makefunction(2) # =&gt; we capture the closure\nfunc.call(6)    # =&gt; Result equal "12"  \n</code></pre>\n\n<p>it works even when both, "multiply" method and "x" variable,not longer exist. All because the closure capability to remember.</p>\n'}, {'answer_id': 24816814, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 2, 'selected': False, 'text': '<p>In Python, a closure is an instance of a function that has variables bound to it immutably.</p>\n\n<p>In fact, the <a href="https://docs.python.org/3.3/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">data model explains this</a> in its description of functions\' <code>__closure__</code> attribute: </p>\n\n<blockquote>\n  <p>None or a <strong>tuple of cells</strong> that contain bindings for the function’s free variables. Read-only</p>\n</blockquote>\n\n<p>To demonstrate this:</p>\n\n<pre><code>def enclosure(foo):\n    def closure(bar):\n        print(foo, bar)\n    return closure\n\nclosure_instance = enclosure(\'foo\')\n</code></pre>\n\n<p>Clearly, we know that we now have a function pointed at from the variable name <code>closure_instance</code>. Ostensibly, if we call it with an object, <code>bar</code>, it should print the string, <code>\'foo\'</code> and whatever the string representation of <code>bar</code> is.</p>\n\n<p>In fact, the string \'foo\' <em>is</em> bound to the instance of the function, and we can directly read it here, by accessing the <code>cell_contents</code> attribute of the first (and only) cell in the tuple of the <code>__closure__</code> attribute:</p>\n\n<pre><code>&gt;&gt;&gt; closure_instance.__closure__[0].cell_contents\n\'foo\'\n</code></pre>\n\n<p>As an aside, cell objects are described in the C API documentation:</p>\n\n<blockquote>\n  <p><a href="https://docs.python.org/2/c-api/cell.html" rel="nofollow">"Cell" objects are used to implement variables referenced by multiple\n  scopes</a></p>\n</blockquote>\n\n<p>And we can demonstrate our closure\'s usage, noting that <code>\'foo\'</code> is stuck in the function and doesn\'t change:</p>\n\n<pre><code>&gt;&gt;&gt; closure_instance(\'bar\')\nfoo bar\n&gt;&gt;&gt; closure_instance(\'baz\')\nfoo baz\n&gt;&gt;&gt; closure_instance(\'quux\')\nfoo quux\n</code></pre>\n\n<p>And nothing can change it:</p>\n\n<pre><code>&gt;&gt;&gt; closure_instance.__closure__ = None\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in &lt;module&gt;\nTypeError: readonly attribute\n</code></pre>\n\n<h3>Partial Functions</h3>\n\n<p>The example given uses the closure as a partial function, but if this is our only goal, the same goal can be accomplished with <code>functools.partial</code></p>\n\n<pre><code>&gt;&gt;&gt; from __future__ import print_function # use this if you\'re in Python 2.\n&gt;&gt;&gt; partial_function = functools.partial(print, \'foo\')\n&gt;&gt;&gt; partial_function(\'bar\')\nfoo bar\n&gt;&gt;&gt; partial_function(\'baz\')\nfoo baz\n&gt;&gt;&gt; partial_function(\'quux\')\nfoo quux\n</code></pre>\n\n<p>There are more complicated closures as well that would not fit the partial function example, and I\'ll demonstrate them further as time allows.</p>\n'}, {'answer_id': 32726068, 'author': 'thiagoh', 'author_id': 889213, 'author_profile': 'https://Stackoverflow.com/users/889213', 'pm_score': 1, 'selected': False, 'text': '<p>Here is an example of Python3 closures </p>\n\n<pre><code>def closure(x):\n    def counter():\n        nonlocal x\n        x += 1\n        return x\n    return counter;\n\ncounter1 = closure(100);\ncounter2 = closure(200);\n\nprint("i from closure 1 " + str(counter1()))\nprint("i from closure 1 " + str(counter1()))\nprint("i from closure 2 " + str(counter2()))\nprint("i from closure 1 " + str(counter1()))\nprint("i from closure 1 " + str(counter1()))\nprint("i from closure 1 " + str(counter1()))\nprint("i from closure 2 " + str(counter2()))\n\n# result\n\ni from closure 1 101\ni from closure 1 102\ni from closure 2 201\ni from closure 1 103\ni from closure 1 104\ni from closure 1 105\ni from closure 2 202\n</code></pre>\n'}, {'answer_id': 47981346, 'author': 'Dinesh Sonachalam', 'author_id': 5674391, 'author_profile': 'https://Stackoverflow.com/users/5674391', 'pm_score': 3, 'selected': False, 'text': '<pre><code># A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.\n\n# Defining a closure\n\n# This is an outer function.\ndef outer_function(message):\n    # This is an inner nested function.\n    def inner_function():\n        print(message)\n    return inner_function\n\n# Now lets call the outer function and return value bound to name \'temp\'\ntemp = outer_function("Hello")\n# On calling temp, \'message\' will be still be remembered although we had finished executing outer_function()\ntemp()\n# Technique by which some data(\'message\') that remembers values in enclosing scopes \n# even if they are not present in memory is called closures\n\n# Output: Hello\n</code></pre>\n\n<p><strong>Criteria to met by Closures are:</strong></p>\n\n<ol>\n<li>We must have nested function.</li>\n<li>Nested function must refer to the value defined in the enclosing function.</li>\n<li>Enclosing function must return the nested function.</li>\n</ol>\n\n<hr>\n\n<pre><code># Example 2\ndef make_multiplier_of(n): # Outer function\n    def multiplier(x): # Inner nested function\n        return x * n\n    return multiplier\n# Multiplier of 3\ntimes3 = make_multiplier_of(3)\n# Multiplier of 5\ntimes5 = make_multiplier_of(5)\nprint(times5(3)) # 15\nprint(times3(2)) #  6\n</code></pre>\n'}, {'answer_id': 49885629, 'author': 'Nitish Chauhan', 'author_id': 4708210, 'author_profile': 'https://Stackoverflow.com/users/4708210', 'pm_score': 1, 'selected': False, 'text': '<p>we all have used <strong>Decorators</strong> in python. They are nice examples to show what are closure functions in python.</p>\n\n<pre><code>class Test():\n    def decorator(func):\n        def wrapper(*args):\n            b = args[1] + 5\n            return func(b)\n        return wrapper\n\n@decorator\ndef foo(val):\n    print val + 2\n\nobj = Test()\nobj.foo(5)\n</code></pre>\n\n<p>here final value is 12</p>\n\n<p>Here, the wrapper function is able to access func object because wrapper is "lexical closure", it can access it\'s parent attributes.\nThat is why, it is able to access func object.</p>\n'}, {'answer_id': 50302797, 'author': 'Eunjung Lee', 'author_id': 9779393, 'author_profile': 'https://Stackoverflow.com/users/9779393', 'pm_score': 1, 'selected': False, 'text': '<p>I would like to share my example and an explanation about closures. I made a python example, and two figures to demonstrate stack states.</p>\n\n<pre><code>def maker(a, b, n):\n    margin_top = 2\n    padding = 4\n    def message(msg):\n        print(\'\\n’ * margin_top, a * n, \n            \' ‘ * padding, msg, \' ‘ * padding, b * n)\n    return message\n\nf = maker(\'*\', \'#\', 5)\ng = maker(\'\uf0a7\', \'♥’, 3)\n…\nf(\'hello\')\ng(‘good bye!\')\n</code></pre>\n\n<p>The output of this code would be as follows:</p>\n\n<pre><code>*****      hello      #####\n\n\uf0a7\uf0a7\uf0a7      good bye!    ♥♥♥\n</code></pre>\n\n<p>Here are two figures to show stacks and the closure attached to the function object.</p>\n\n<p><a href="https://i.stack.imgur.com/q34kz.jpg" rel="nofollow noreferrer">when the function is returned from maker</a></p>\n\n<p><a href="https://i.stack.imgur.com/Jwssu.jpg" rel="nofollow noreferrer">when the function is called later</a></p>\n\n<p>When the function is called through a parameter or a nonlocal variable, the code needs local variable bindings such as margin_top, padding as well as a, b, n. In order to ensure the function code to work, the stack frame of the maker function which was gone away long ago should be accessible, which is backed up in the closure we can find along with the \'message\'s function object.</p>\n'}]
['https://Stackoverflow.com/questions/13857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1649/']