On Thu, 16 Oct 2008 17:05:40 +1300, Lawrence D'Oliveiro wrote: > In message <[EMAIL PROTECTED]>, Steven D'Aprano > wrote: > >> On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote: >> >>> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote: >>> >>>> No, it always contains the default argument because default values >>>> are created just ONE TIME > <http://effbot.org/pyfaq/why-are-default-values-shared-between- objects>... >>> >>> >>> Wow, it's a very "dangerous" behavior ... >> >> No, it's very *useful* behaviour. > > Can you give an example of how useful it is? Something worth the pain of > newbies tripping over it every week?
Did you read the effbot's explanation in the link above? He gives two examples, memoization and binding of locals. The second example is especially interesting, because that's also a Gotcha for newbies (not just noobs either...), and the solution to that specific gotcha is Python's use of define-time binding of default values. >>> callbacks = [None]*4 >>> for i in xrange(len(callbacks)): ... callbacks[i] = lambda s: '%d %s' % (i, s) ... >>> for cb in callbacks: ... print cb('string') ... 3 string 3 string 3 string 3 string Newbies get confused by this almost as often as by the default value semantics, but the simplest solution to this gotcha is to use Python's default values: >>> for i in xrange(len(callbacks)): ... callbacks[i] = lambda s, i=i: '%d %s' % (i, s) ... >>> for cb in callbacks: ... print cb('string') ... 0 string 1 string 2 string 3 string If Python re-evaluated the default value i=i at runtime, the above would break. -- Steven -- http://mail.python.org/mailman/listinfo/python-list