Je t’embrasse Salutations from Silicon Valley, California

13Apr/110

Pretty-Print for Python Dict/List/Tuple

I wrote this a while ago to give me a better view into complex nested structures Dict-of-List-of-Dict, etc.
The benefit here is that these functions can be wrapped as a Python module, and imported to all your projects for debug.

Enjoy.

import sys

def newline():
    sys.stdout.write('\n')
    sys.stdout.flush()

def __type_quote(this):
    if type(this) == type(1): return str(this)
    else: return "'"+str(this)+"'"

def __has_children(parent):
    answer = False
    valid = [type([1,2]), type((1,2)), type({1:2})]
    if type(parent) == type([1,2]):
        for each in parent:
            if type(each) in valid: answer = True
    elif type(parent) == type((1,2)):
        answer = __has_children(list(parent))
    elif type(parent) == type({1:2}):
        for (key, value) in parent.items():
            if type(value) in valid: answer = True
    return answer

def __print_list(list, n=0, shrink=False, opener="[", closer="]"):
    assert type(list) == type([])
    sp = "".join([" "]*n)
    valid = [type([1,2]), type((1,2)), type({1:2})]

    # find the max index (for spacing of the format string)
    size = len(list)
    fstring = "%s  %-"+str(size)+"s: "

    # start printing stuff
    sys.stdout.write(opener)
    sys.stdout.flush()
    list.sort()
    for index in range(len(list)):
        newline()
        sys.stdout.write(fstring%(sp, index))
        sys.stdout.flush()
        this = list[index]
        if not __has_children(this) and type(this) in valid:
            if type(this) == type([1,2]) and len(this) > 10 and shrink == True:
                sys.stdout.write("['%s', ... ,'%s']"%(this[0], this[-1]))
                sys.stdout.flush()
            else:
                sys.stdout.write(str(this))
                sys.stdout.flush()
        elif type(this) == type([1,2]): __print_list(this, n+4+size)
        elif type(this) == type({1:2}): __print_dict(this, n+4+size)
        elif type(this) == type((1,2)): __print_tuple(this, n+4+size)
        else:
            sys.stdout.write(str(this))
            sys.stdout.flush()
    if len(list) > 0:
        newline()
        sys.stdout.write("%s%s"%(sp, closer))
    else: sys.stdout.write("%s"%closer)
    sys.stdout.flush()

def __print_dict(dict, n=0, shrink=False):
    assert type(dict) == type({1:2})
    sp = "".join([" "]*n)
    valid = [type([1,2]), type((1,2)), type({1:2})]

    # find the max key-size (for spacing of the format string)
    size = 0
    for key in dict.keys():
        if len(str(key)) > size: size = len(str(key))
    fstring = "%s  %-"+str(size)+"s: "

    # start printing stuff
    sys.stdout.write("{")
    sys.stdout.flush()
    keys = dict.keys()
    keys.sort()
    for key in keys:
        newline()
        sys.stdout.write(fstring%(sp, key))
        sys.stdout.flush()
        this = dict[key]
        if not __has_children(this) and type(this) in valid:
            if type(this) == type([1,2]) and len(this) > 10 and shrink == True:
                sys.stdout.write("[%s, ... ,%s]"%(__type_quote(this[0]),
                                                  __type_quote(this[-1])))
                sys.stdout.flush()
            else:
                sys.stdout.write(str(this))
                sys.stdout.flush()
        elif type(this) == type([1,2]): __print_list(this, n+4+size)
        elif type(this) == type({1:2}): __print_dict(this, n+4+size)
        elif type(this) == type((1,2)): __print_tuple(this, n+4+size)
        else:
            sys.stdout.write(__type_quote(this))
            sys.stdout.flush()
    if len(dict.keys()) > 0:
        newline()
        sys.stdout.write("%s}"%sp)
    else: sys.stdout.write("}")
    sys.stdout.flush()

def __print_tuple(tup, n=0, shrink=False):
    assert type(tup) == type((1,2))
    __print_list(list(tup), n, shrink, opener="(", closer=")")

def print_dict(d):
    __print_dict(d, shrink=True)
    newline()

def print_list(l):
    __print_list(l, shrink=True)
    newline()

def print_tuple(t):
    __print_tuple(t, shrink=True)
    newline()
Filed under: Python No Comments