Re: bug or feature?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: bug or feature?

From: Fredrik Lundh <fredrik@pythonware.com>
Date: Thu Oct 06 2005 - 08:53:55 CEST

Steven D'Aprano wrote:

> I suppose someone might be able to come up with code that deliberately
> uses this feature for good use

argument binding is commonly used for optimization, and to give simple
functions persistent storage (e.g. memoization caches).

more importantly, it's the standard pydiom for passing object *values* (of
any kind) into an inner scope:

    x = something

    def myfunc(arg, x=x):
        # myfunc needs the current value, not whatever x
        # happens to be when the function is called

here's a typical gotcha:

    for i in range(10):
        def cb():
            print "slot", i, "fired"
        register_callback(slot=i, callback=cb)

to make this work as expected, you have to do

    for i in range(10):
        def cb(i=i):
            print "slot", i, "fired"
        register_callback(slot=i, callback=cb)

</F>
Received on Sat Oct 15 04:12:30 2005