Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is how I think of a closure....</p> <p>A function object consists of two things. The first thing is the code for the function, the second is the scope in which it executes. In a closure, the scope in which the function executes and the code are detached from each other. The same code can execute in a variety of scopes.</p> <p>If this were allowed in a completely unrestricted way it would result in great confusion. Even when it's something as loose as dynamic scoping (the function inherits the scope of the place where it was called from) it becomes very confusing.</p> <p>Closures are a convenient way of specifying scope rules that make a lot of sense because they only require reading the code instead of tracing it. In a closure, the function gets the scope of where it was declared. If it was declared while executing another function, it gets the scope of that specific instance of the function's stack. This is a lot simpler and easier to understand than being able to give the closure and arbitrary scope, or dynamic scoping.</p> <p>Here is an example of a trivial closure in Python:</p> <pre><code>def outer(): def closure(): pass return closure </code></pre> <p>Here the function <code>closure</code> is a closure. It doesn't actually use any variables from the scope in which it was defined, so it's pretty trivial, but it still is one.</p> <p>Here is a not-so-trivial, but still simple closure in Python:</p> <pre><code> def outer(x): def closure(): return x return closure f1 = outer(5) f2 = outer(6) </code></pre> <p>Calling <code>f1()</code> will return 5 and calling <code>f2()</code> will return 6. As you can see, the function <code>closure</code> is part code, and part scope.</p> <p>When <code>outer(5)</code> is called, it creates a stack entry for the call that contains a version of the variable <code>x</code> holding the value 5. It then declares the function <code>closure</code> which gets that scope.</p> <p>When <code>outer(6)</code> is called, it creates a stack entry for the call that contains a version of the variable <code>x</code> holding the value 6. It then declares the function <code>closure</code> which gets that scope.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload