aboutsummaryrefslogtreecommitdiff
path: root/tools/ccc/ccclib/Util.py
blob: 0924e8c2489060e7ef098bead81248bf0510e102 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def any_true(list, predicate):
    for i in list:
        if predicate(i):
            return True
    return False

def any_false(list, predicate):
    return any_true(list, lambda x: not predicate(x))

def all_true(list, predicate):
    return not any_false(list, predicate)

def all_false(list, predicate):
    return not any_true(list, predicate)

def prependLines(prependStr, str):
    return ('\n'+prependStr).join(str.splitlines())

def pprint(object, useRepr=True):
    def recur(ob):
        return pprint(ob, useRepr)
    def wrapString(prefix, string, suffix):
        return '%s%s%s' % (prefix, 
                           prependLines(' ' * len(prefix),
                                        string),
                           suffix)
    def pprintArgs(name, args):
        return wrapString(name + '(', ',\n'.join(map(recur,args)), ')')
                            
    if isinstance(object, tuple):
        return wrapString('(', ',\n'.join(map(recur,object)), 
                          [')',',)'][len(object) == 1])
    elif isinstance(object, list):
        return wrapString('[', ',\n'.join(map(recur,object)), ']')
    elif isinstance(object, set):
        return pprintArgs('set', list(object))
    elif isinstance(object, dict):
        elts = []
        for k,v in object.items():
            kr = recur(k)
            vr = recur(v)
            elts.append('%s : %s' % (kr, 
                                     prependLines(' ' * (3 + len(kr.splitlines()[-1])),
                                                  vr)))
        return wrapString('{', ',\n'.join(elts), '}')
    else:
        if useRepr:
            return repr(object)
        return str(object)

def prefixAndPPrint(prefix, object, useRepr=True):
    return prefix + prependLines(' '*len(prefix), pprint(object, useRepr))