bug or feature?

Fredrik Lundh fredrik at pythonware.com
Thu Oct 6 08:53:55 CEST 2005


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>






More information about the Python-list mailing list