首页 > 解决方案 > Print nested object like python code (style guide)

问题描述

I'd like to achieve a string representation of arbitrarily nested lists, tuples, dicts, ints, strings, bools, and None values that fulfills the following requirements:

Is there some pythonic way to do it or do I have to code that function my own?

Here is an example:

test_obj = [['foo', 'bar'], ['foo', 'bar'], (1, 'Tupple'),
            {'key': 'value', 'fookey': None, 'barkey': True,
             'nested': ['a', 'nice', 'list']}]

Should result in something like this:

[
    [
        "foo",
        "bar"
    ],
    [
        "foo",
        "bar"
    ],
    (
        1,
        "Tupple"
    ),
    {
        "fookey": None,
        "key": "value",
        "nested": [
            "a",
            "nice",
            "list"
        ],
        "barkey": True
    }
]

I've tried pprint.pprint(test_obj, indent=4, width=1) which is close but it puts opening/closing brackets in one line:

>>> pprint.pprint(test_obj, indent=4, width=1)
[   [   'foo',
        'bar'],
    [   'foo',
        'bar'],
    (   1,
        'Tupple'),
    {   'barkey': True,
        'fookey': None,
        'key': 'value',
        'nested': [   'a',
                      'nice',
                      'list']}]

I also tried json.dumps(test_obj, indent=4) which is pretty much it but JSON does not know what tuples are and the keywords are a little different (null <-> None, true <-> True, …)

标签: pythonpython-3.x

解决方案


If you want to print with your custom format, write a recursive function, e.g.:

def pprint(obj,depth=0,indent='    '):
    if isinstance(obj,list):
        print('[')
        for x in obj:
            print(indent*(depth+1), end='')
            pprint(x,depth+1,indent)
        print(indent*depth+']')
    elif isinstance(obj,tuple):
        print('(')
        for x in obj:
            print(indent*(depth+1), end='')
            pprint(x,depth+1,indent)
        print(indent*depth+')')
    elif isinstance(obj,dict):
        print('{')
        for k, v in obj.items():
            print(indent*(depth+1)+repr(k)+': ', end='')
            pprint(v,depth+1,indent)
        print(indent*depth+'}')
    else:
        print(repr(obj))

推荐阅读