setting variables in outer functions

Hrvoje Niksic hniksic at
Thu Nov 1 00:27:46 CET 2007

"Chris Mellon" <arkanes at> writes:

> I have no idea why someone who already has a working, object system
> would want to implement their own on top of closures.

This subthread is getting ridiculous -- closures are *not* useful only
for implementing object systems!  The object system thing is just a
method of teaching abstractions popularized by SICP.  Abstractions
normally taken for granted, such as objects, or even expression
evaluation, are implemented from scratch, using only the most basic
primitives available.  In a Lisp-like language with lexical scope, the
most basic storage primitive is the lexical environment itself[1].

In real-life code, closures are used to implement callbacks with
automatic access to their lexical environment without the need for the
bogus additional "void *" argument one so often sees in C callbacks,
and without communication through global variables.  If the callbacks
can access variables in the outer scope, it's only logical (and
useful) for them to be able to change them.  Prohibiting modification
reduces the usefulness of closures and causes ugly workarounds such as
the avar[0] pattern.

If closures were useful only for implementing bogus object systems,
neither they nor "nonlocal" would have made it to Python in the first

An illustration of that principle is an implementation of cons, the
most primitive Lisp storage type, without the use of a higher-level
storage object (such as a two-element vector):

(defun cons (x y)
  (lambda (op)
    (if op x y)))
(defun car (cons) (funcall cons t))
(defun cdr (cons) (funcall cons nil))

More information about the Python-list mailing list