A unicode friendly pretty print function for Python

Using Python 2.7 I struggle to get pprint to work well with unicode. So I wrote my own function for handling complex structures made of dicts and lists that contain linguistic data stored in utf-8.

This function will generate a human-friendly unicode representation of any arbitrary object containing objects of type list, dict, unicode, str, and any native Python number. The function could be easily edited to make it more abstract if needed.

The basic logic could use a for loop, but it seemed to me neater and more Pythonic to use a self-referential function.

import io, itertools
from numbers import Number

def uppprint(obj,indent_level=0):
    indent = u'\t'
    for i in range(0,indent_level):
        indent += u'\t'
    out = u''
    if isinstance(obj,unicode):
        out += u'u"'+obj+u'"'
    elif isinstance(obj,str):
        out += u'u"'+unicode(obj)+u'"'
    elif isinstance(obj,list):
        out += u'[\n'
        for item in obj:
            out += indent+u'\t'+upp(item,indent_level+1)+u',\n'
        out += indent+u']'
    elif isinstance(obj,dict):
        out += u'{\n'
        for key, item in obj.iteritems():
            out += indent+u'\t'+u'u"'+key+u'" : '+upp(item,indent_level+1)+u',\n'
        out += indent+u'}'
    elif isinstance(obj,Number):
        out += unicode(obj)
    else:
        out += u'u"'+unicode(obj)+u'"'
    return out

Usage example to produce a module that makes a data structure easily callable in later code. Just supply your own “data” object:

pyheader = u'''#!/usr/bin/python
# -*- coding: utf-8 -*-

'''

with io.open('upp_output_sample.py', 'w', encoding='utf-8') as file:
    file.write(pyheader)
    file.write(u'data=')
    file.write(upp(data))
Creative Commons License
This work by pete is licensed under a Creative Commons Attribution 4.0 International