nested functions

Michael Hudson mwh21 at
Fri Feb 25 15:30:24 CET 2000

=?ISO-8859-1?Q?Fran=E7ois_Pinard?= <pinard at> writes:

> "Tim Peters" <tim_one at> écrit:
> > [Alexander V. Voinov]
> > > Please remind me, if there are any performance penalties in nesting
> > > functions ...
> > [...] a function object has to be allocated [...each time through...],
> > a pointer to the global namespace needs to be installed, and current
> > bindings for optional arguments (if any) need to be captured.
> It looks more powerful than I imagined!  Isn't this one more step towards
> lexical closures? :-)

Oh yes.  If you've read SICP, then you'll probably remember the
running example along the lines of:

(define (make-balance amount)
  (define (enquire) amount)
  (define (deposit a) (set! amount (+ amount a)))
  (define (withdraw a) (set! amount (- amount a)))
  (list enquire deposit withdraw))

(let* ((l (make-balance 100))
       (e (car l))
       (d (cadr l))
       (w (caddr l)))
  (display (e))  (newline)
  (d 30)
  (display (e))  (newline))

which should print


This can be done in Python:

def make_balance(n):
    a = [n]
    def enquire(a=a): return a[0]
    def deposit(x,a=a): a[0] = a[0] + x
    def withdraw(x,a=a): a[0] = a[0] - x
    return enquire,deposit,withdraw

print e1(),e2()
print e1(),e2()

which should print:

100 100
130 100

Thing is, while this is a (vaguely) sensible way to behave in scheme,
it's demented in Python.  Use a class.

just-because-you-can-don't-think-you-should-ly y'rs

very few people approach me in real life and insist on proving they are
drooling idiots.                         -- Erik Naggum, comp.lang.lisp

More information about the Python-list mailing list