home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-rdflib / rdflib / sparql / bison / Util.py < prev   
Encoding:
Python Source  |  2007-04-04  |  1.2 KB  |  30 lines

  1. class ListRedirect(object):
  2.     """
  3.     A utility class for lists of items joined by an operator.  ListRedirects with length 1
  4.     are a special case and are considered equivalent to the item instead of a list containing it.
  5.     The reduce function is used for normalizing ListRedirect to the single item (and calling reduce on it recursively)
  6.     """
  7.     reducable = True
  8.     def __getattr__(self, attr):
  9.         if hasattr(self._list, attr):
  10.             return getattr(self._list, attr)
  11.         raise AttributeError, '%s has no such attribute %s' % (repr(self), attr)
  12.  
  13.     def __iter__(self):
  14.         for i in self._list:
  15.             yield i
  16.  
  17.     def reduce(self):
  18.         if self.reducable and len(self._list) == 1:
  19.             singleItem = self._list[0]
  20.             if isinstance(singleItem,ListRedirect):
  21.                 return singleItem.reduce()
  22.             else:
  23.                 return singleItem
  24.         else:
  25.             return type(self)([isinstance(item,ListRedirect) and item.reduce() or item for item in self._list])
  26.  
  27. #Utility function for adding items to the front of a list
  28. def ListPrepend(item,list):
  29.     #print "adding %s to front of %s"%(item,list)
  30.     return [item] + list