Dynamic methods and lambda functions

Mark Wooding mdw at distorted.org.uk
Mon Jan 26 05:20:30 EST 2009


Michael Torrie <torriem at gmail.com> writes:

> Basically, don't use a lambda.  Create a real, local closure with a
> nested def block.  That way the closure is created every time the
> parent function is called.

Nope.  I explained the real problem quite clearly, and it's to do with
the difference between binding and assignment.

What's the difference between these two pieces of code?

        ## First
        def __init__(self):
          for n, v in props:
            setattr(Person, '_' + n, v)
            setattr(Person, n, lambda self: getattr(self, '_' + n))

        ## Second
        def __init__(self):
          for n, v in props:
            setattr(Person, '_' + n, v)
            def hack(self): return getattr(self, '_' + n)
            setattr(Person, n, hack)

> Lambda expressions are only ever compiled once during execution.

The same is true of `def' bodies.

-- [mdw]



More information about the Python-list mailing list