Package joy ::
Module misc
|
|
1
2
3
4
5
6
7
8
9
10 """
11 misc.py defines several useful functions that don't rightly belong in any obvious location
12
13 Functions
14 ---------
15
16 curry -- Curry a function, returning a callable with the value of the initial parameters pre-selected. One of the mainstays of functional programming.
17
18 printExc -- Print a formatted stack-trace to standard error
19
20 loadCSV -- Load a CSV file into a list of lists
21
22 inlineCSV -- Similar to loadCSV, but takes the CSV text from a multiline python string
23 """
24
25 import traceback
26 import sys
27
28 -def curry(fn, *cargs, **ckwargs):
29 """
30 Curry a function, returning a callable with the value of the
31 initial parameters pre-selected. For any function f
32 curry(f,*arg0)(*arg1,**kw) f(x,*(arg0+arg1),**kw)
33 so, for example:
34 f(x,y) = curry(f,x)(y) = curry(f,x,y)()
35 """
36 def call_fn(*fargs, **fkwargs):
37 d = ckwargs.copy()
38 d.update(fkwargs)
39 return fn(*(cargs + fargs), **d)
40 return call_fn
41
43 """
44 Print a formatted stack-trace to standard error
45 """
46
47 if exinfo is None:
48 exinfo = sys.exc_info()
49 msg = ["<< "*10+"\n"]
50 msg.extend(traceback.format_exception(*exinfo))
51 msg.append(">> "*10+"\n")
52 sys.stderr.writelines(msg)
53
55 """
56 Load a CSV file into a list of lists, converting empty cells into
57 None, numbers as floats and quoted strings as strings.
58
59 In addition to standard CSV format, empty (white only) lines and
60 lines starting with "#" are ignored
61 """
62 if type(fn)==str:
63 f = open(fn,'r')
64 else:
65 assert iter(fn),"Must be iterable returning lines"
66 f = fn
67 def convert(x):
68 x = x.strip()
69 if not x or x=='""': return None
70 if x[0]=='"': return x[1:-1]
71 return float(x)
72 res = [
73 [ convert(x) for x in l.split(",") ]
74 for l in f if l.strip() and l[:1]!="#"
75 ]
76 if type(fn)==str:
77 f.close()
78 return res
79
81 """
82 Similar to loadCSV, but takes the CSV text from a multiline
83 python string, e.g.
84
85 >>> sheet = inlineCSV('''
86 ... # Non-CSV Unix shell style comments and empty lines are ignored
87 ... , "sparrow", "banana"
88 ... "weight", 5, 1
89 ... ''')
90 """
91 return loadCSV(( l for l in txt.split("\n") ))
92