Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A <b>lambda</b> is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.</p> <p>A <b>closure</b> is any function which <b>closes over</b> the <b>environment</b> in which it was defined. This means that it can access variables not in its parameter list. Examples:</p> <pre><code>def func(): return h def anotherfunc(h): return func() </code></pre> <p>This will cause an error, because <code>func</code> does not <b>close over</b> the environment in <code>anotherfunc</code> - <code>h</code> is undefined. <code>func</code> only closes over the global environment. This will work:</p> <pre><code>def anotherfunc(h): def func(): return h return func() </code></pre> <p>Because here, <code>func</code> is defined in <code>anotherfunc</code>, and in python 2.3 and greater (or some number like this) when they <i>almost</i> got closures correct (mutation still doesn't work), this means that it <b>closes over</b> <code>anotherfunc</code>'s environment and can access variables inside of it. In Python 3.1+, mutation works too when using <a href="http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal" rel="noreferrer">the <code>nonlocal</code> keyword</a>.</p> <p>Another important point - <code>func</code> will continue to close over <code>anotherfunc</code>'s environment even when it's no longer being evaluated in <code>anotherfunc</code>. This code will also work:</p> <pre><code>def anotherfunc(h): def func(): return h return func print anotherfunc(10)() </code></pre> <p>This will print 10.</p> <p>This, as you notice, has nothing to do with <b>lambda</b>s - they are two different (although related) concepts.</p>
 

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