Here is my pretty (alternative pretty print function alpha 0.1)

TrustyTony 0 Tallied Votes 2K Views Share

Here is my newest baby, the module, born today, which I start to use instead of pprint module.

Reason to make this (in addition to that it is possible to do) is that I had this problem, sorry long, LONG example:

UPDATE: take out the

or j

that was by mistake left from development.
Example is starting from line 43 from different run with longer a variable defined before expressions.

## The problem with prettyprint module
>>> a=['a','b','c']*4
>>> pprint(a)
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
>>> a=['a','b','c']*10
>>> pprint(a)
['a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c']
>>>
## i like this better
>> pretty.ppr(a)

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
## more hierarchy
>>> a[4]=[['a','b','c']]*2
>>> a
['a', 'b', 'c', 'a', [['a', 'b', 'c'], ['a', 'b', 'c']], 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
## lets first show my way
>>> pretty.ppr(a)

['a', 'b', 'c', 'a',
  [
    ['a', 'b', 'c'],
    ['a', 'b', 'c']], 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
## pprint way
>>> pprint(a)
['a',
 'b',
 'c',
 'a',
 [['a', 'b', 'c'], ['a', 'b', 'c']],
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c',
 'a',
 'b',
 'c']
### more use examples
>>> ppr(4*[(['a','b','c','d'],)*4])

[
  (
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d']),
  (
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d']),
  (
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d']),
  (
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d'],
    ['a','b','c','d'])]
## You can not say like this
>>> ppr(4*[([None*4],)*4])

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    ppr(4*[([None*4],)*4])
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

## You must say not like this
>>> ppr(4*[([[None]*4],)*4])

[
  (
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]]),
  (
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]]),
  (
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]]),
  (
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]],
    [
      [None,None,None,None]])]

 ## but like this
>>> ppr(4*[([None]*4,)*4])

[
  (
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None]),
  (
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None]),
  (
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None]),
  (
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None],
    [None,None,None,None])]
## Success!
""" pretty.py prettyprint module version alpha 0.1
    mypr: pretty string function
    ppr:  print of the pretty string
    ONLY list and tuple prettying implemented!
"""
def mypr(w, i = 0, indent = 2) :
    """ w = datastructure, i = indent level, indent = step size for indention """
    startend = {list : '[]', tuple : '()'}
    if type(w) in (list, tuple) :
        start, end = startend[type(w)]
        pr = [mypr(j, i + indent) or j for j in w]
        return '\n' + ' ' * i + start + ', '.join(pr) + end
    else :  return repr(w)

def ppr(w) :
    """ see mypr, this is only print of mypr(w) """
    print mypr(w)

Dani AI

Generated

Nice, small and practical printer from — keeps nested lists/tuples compact while letting you control indentation and the nl prefix (useful for comment prefixes). A few focused suggestions that keep the current design but make it safer, more flexible and Python-3 friendly:

  • Prefer isinstance(obj, (list, tuple)) rather than type(...) in (...) so subclasses behave correctly.
  • Make the scalar formatter configurable instead of hardcoding repr or str. repr keeps output eval-able (as you noted), str is often prettier — expose a reprfunc= parameter so callers choose. 's Line 13 suggestion to try str(w) is valid, but offer it as an option.
  • Prevent infinite recursion on self-referential structures by tracking seen object ids (return a short marker like <...>). Also build strings with list-append + ''.join(...) or io.StringIO for speed instead of repeated concatenation.
  • For Python 3: make ppr call print(s) or simply return the string and let callers print — and ensure bytes/unicode handling is explicit.

Example pattern (safe recursion + configurable formatter):

def format_obj(obj, indent=2, reprfunc=repr, nl='\\n', _seen=None):
    if _seen is None:
        _seen = set()
    oid = id(obj)
    if oid in _seen:
        return '<...>'
    if isinstance(obj, (list, tuple)):
        _seen.add(oid)
        parts = [format_obj(x, indent, reprfunc, nl, _seen) for x in obj]
        _seen.remove(oid)
        open_, close = ('[', ']') if isinstance(obj, list) else ('(', ')')
        return nl + open_ + ', '.join(parts) + close
    return reprfunc(obj)

Final notes: avoid eval on pretty output from untrusted sources, consider optional maxitems to truncate huge sequences, and add dict/set support if you want broader coverage. These changes keep your simple API while addressing correctness and robustness.

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Here is pretty alpha 0.2. I forgot to include the i and indent for ppr also. I added possibility for the initial newline suppression or for example doubling by adding the nl keyword parameter.

>>> a=range(10)
>>> a.insert(5,[range(i) for i in range(10)])
>>> a
[0, 1, 2, 3, 4, [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]
>>> import pretty
>>> pretty.ppr(a,indent=6)

[0, 1, 2, 3, 4, 
      [
        [], 
        [0], 
        [0, 1], 
        [0, 1, 2], 
        [0, 1, 2, 3], 
        [0, 1, 2, 3, 4], 
        [0, 1, 2, 3, 4, 5], 
        [0, 1, 2, 3, 4, 5, 6], 
        [0, 1, 2, 3, 4, 5, 6, 7], 
        [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]
>>> pretty.ppr(a,i=16)

                [0, 1, 2, 3, 4, 
                  [
                    [], 
                    [0], 
                    [0, 1], 
                    [0, 1, 2], 
                    [0, 1, 2, 3], 
                    [0, 1, 2, 3, 4], 
                    [0, 1, 2, 3, 4, 5], 
                    [0, 1, 2, 3, 4, 5, 6], 
                    [0, 1, 2, 3, 4, 5, 6, 7], 
                    [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]
>>>

Here the code:

""" pretty.py prettyprint module version alpha 0.2
    mypr: pretty string function
    ppr:  print of the pretty string
    ONLY list and tuple prettying implemented!
"""
def mypr(w, i = 0, indent = 2, nl='\n') :
    """ w = datastructure, i = indent level, indent = step size for indention """
    startend = {list : '[]', tuple : '()'}
    if type(w) in (list, tuple) :
        start, end = startend[type(w)]
        pr = [mypr(j, i + indent) for j in w]
        return nl + ' ' * i + start + ', '.join(pr) + end
    else :  return repr(w)

def ppr(w, i = 0, indent = 2, nl='\n') :
    """ see mypr, this is only print of mypr with same parameters """
    print mypr(w, i, indent, nl)
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Alpha 0.21
Here is really functioning version of changeable nl parameter. nl was missing from recursive function call.

By the way, Python accept pretty printed output as input in programs, so it is possible to ppr complicated lists and cut and paste instead of trying to do it nicely manually.

""" pretty.py prettyprint module version alpha 0.21
    mypr: pretty string function
    ppr:  print of the pretty string
    ONLY list and tuple prettying implemented!
"""
def mypr(w, i = 0, indent = 2, nl = '\n') :
    """ w = datastructure, i = indent level, indent = step size for indention """
    startend = {list : '[]', tuple : '()'}
    if type(w) in (list, tuple) :
        start, end = startend[type(w)]
        pr = [mypr(j, i + indent, indent, nl) for j in w]
        return nl + ' ' * i + start + ', '.join(pr) + end
    else :  return repr(w)

def ppr(w, i = 0, indent = 2, nl = '\n') :
    """ see mypr, this is only print of mypr with same parameters """
    print mypr(w, i, indent, nl)
>>> ppr(a, nl='\n#')

#[0, 1, 2, 3, 4, 5, 6, 
#  [
#    [0], 
#    [0, 1], 
#    [0, 1, 2], 
#    [0, 1, 2, 3], 
#    [0, 1, 2, 3, 4], 
#    [0, 1, 2, 3, 4, 5], 
#    [0, 1, 2, 3, 4, 5, 6], 
#    [0, 1, 2, 3, 4, 5, 6, 7], 
#    [0, 1, 2, 3, 4, 5, 6, 7, 8]], 7, 8, 9]
>>> b= [0, 1, 2, 3, 4, 5, 6, 
  [
    [0], 
    [0, 1], 
    [0, 1, 2], 
    [0, 1, 2, 3], 
    [0, 1, 2, 3, 4], 
    [0, 1, 2, 3, 4, 5], 
    [0, 1, 2, 3, 4, 5, 6], 
    [0, 1, 2, 3, 4, 5, 6, 7], 
    [0, 1, 2, 3, 4, 5, 6, 7, 8]], 7, 8, 9]
>>> b
[0, 1, 2, 3, 4, 5, 6, [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 7, 8, 9]
>>>
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Line 13

else :  return repr(w)

Better to change

else :  return str(w)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.