Binding arguments to parameter functions

Calvelo Daniel dcalvelo at pharion.univ-lille2.fr
Fri Oct 27 11:59:37 EDT 2000


Paul-Michael Agapow <p.agapow at ic.ac.uk> wrote:

: But how can you avoid writing a seperate function for each property &
: state? (e.g. to find on any given name, not just "ernie".) The below
: doesn't work, as findWithProperty doesn't know what "name" is:

:    def findWithName (L, name):
:       return findWithProperty (L, lambda x: x.name == name)

: I guess one solution might be to write a function wrapper that binds
: arguments to given parameters in the passed function but this seems like
: too much hard work. Any solutions?

I'm pretty sure this is not the most elegant solution to your overall
problem, but if you are along the lines above, your problem has a quick fix.

You have been bitten by the (I)FSROP (In)Famous Scoping Rules Of Python.

This:

>>> def fwN( L, name ):
...   return findWithProperty( L, lambda x,name=name: x.name == name )
... 
>>> X = fwN( L, "ernie")
>>> X is B
1

is what you wanted. Notice the 'name=name' trick.

And read and reread the FAQ and the reference and what-have-you. You
will be bitten again by that. 

One-day-yes-one-day-Python-nK-will-have-lexical-scoping-ly y'rs,

Daniel.

-- Daniel Calvelo Aros
     calvelo at lifl.fr



More information about the Python-list mailing list