Binding arguments to parameter functions

Paul-Michael Agapow p.agapow at ic.ac.uk
Fri Oct 27 11:29:12 EDT 2000


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]

You could write a function that accepts a function as a parameter, that
assesses each object until one tests true:

   def findWithProperty (L, func):
      for item in L:
         if func (item):
            return item
      return None

   def isErnie (item):
      if item.name == "ernie":
         return 1
      return 0

   X = findWithProperty (L, isErnie)

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?



-- 
Paul-Michael Agapow (p.agapow at ic.ac.uk), Biology, Imperial College
"Pikachu's special power is that he is monophyletic with lagomorphs ..."



More information about the Python-list mailing list