Guest
Public paste!

Marcelo

By: a guest | Feb 17th, 2010 | Syntax: Python | Size: 1.16 KB | Hits: 123 | Expires: Never
Copy text to clipboard
  1. #!/usr/local/bin/python
  2.  
  3.  
  4.  
  5. #### Some function manipulation tools
  6. class NoResult:
  7.     pass
  8.  
  9.  
  10. def apply(f, x):
  11.     if x is NoResult:
  12.         return NoResult
  13.     try:
  14.         if hasattr(f, '__call__'):
  15.             return f(x)
  16.         elif type(f) == type([]):
  17.             for f_i in f:
  18.                 x = apply(f_i, x)
  19.             return x
  20.         elif type(f) == type((1,)):
  21.             assert(len(f) == len(x))
  22.             ret = tuple([apply(f[i], x[i]) for i in range(len(f))])
  23.             if NoResult in ret:
  24.                 return NoResult
  25.             else:
  26.                 return ret
  27.         else:
  28.             return NoResult
  29.     except AssertionError:
  30.         return NoResult
  31.  
  32. #### Some domain-specific functions
  33.  
  34. def stripped(x):
  35.     return x.strip()
  36.  
  37. def split(sep):
  38.     def f(x):
  39.         return x.split(sep)
  40.     return f
  41.  
  42. def capitalized(x):
  43.     return x.capitalize()
  44.  
  45. if __name__ == '__main__':
  46.     DATA = """A,1,marcelo
  47. B,3,paul
  48. """
  49.  
  50.     import StringIO
  51.     datafile = StringIO.StringIO(DATA)
  52.  
  53.     dataparser = [ stripped, split(','), (str, int, capitalized) ]
  54.     for line in datafile:
  55.         print apply(dataparser, line)