Binding arguments to parameter functions

Quinn Dunkan quinn at bolivar.ugcs.caltech.edu
Sat Oct 28 01:29:38 EDT 2000


On Fri, 27 Oct 2000 16:29:12 +0100, Paul-Michael Agapow <p.agapow at ic.ac.uk>
wrote:
>
>I've just struck a problem that I'm sure can be solved in Python but not
>the way I was trying. The below is a very simplified example:
>
>Say you have a some objects with assorted properties in a list and you
>want to fetch objects from the list according to their properties.
>Hence:
>
>   class simple_object:
>      def __init__ (self, name):
>         self.name = name
>
>   A = simple_object ("bert")
>   B = simple_object ("ernie")
>   B = simple_object ("big bird")
>
>   L = [A, B, C]
...
>   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?

The reason your lambda didn't work is because python is not lexically scoped;
it only has two scopes (local and global).  You'd have to pass 'name' in
the arg list explicitly.  name=name is the usual idiom.

If you want to find *all* elements that match a condition, filter does what
you want:

ernies = filter(lambda o: o.name == 'ernie', sesame_cast)
ernies = [ o for o in sesame_cast if o.name == 'ernie' ] # python2 alternative

You could stick a '[0]' on the end to get the first match, but if you always
want to match a single element, I'd suggest that what you really want is a
dictionary:

sesame_d = {}
for c in sesame_cast:
    sesame_d[c.name] = c

ernie = sesame_d['ernie']



More information about the Python-list mailing list