| 1 |
import sys |
| 2 |
|
| 3 |
brackets = {dict: "{}", list: "[]", tuple: "()"} |
| 4 |
|
| 5 |
|
| 6 |
def ppdir(obj, types=None, level=1, stream=sys.stdout, repr=repr): |
| 7 |
"""Pretty-print object attributes""" |
| 8 |
if isinstance(obj, (dict, list, tuple)): |
| 9 |
if isinstance(obj, dict): |
| 10 |
class_ = dict |
| 11 |
elif isinstance(obj, list): |
| 12 |
class_ = list |
| 13 |
elif isinstance(obj, tuple): |
| 14 |
class_ = tuple |
| 15 |
stream.write(brackets[class_][0] + "\n") |
| 16 |
bag = obj |
| 17 |
else: |
| 18 |
bag = dir(obj) |
| 19 |
|
| 20 |
for stuff in bag: |
| 21 |
if isinstance(obj, dict): |
| 22 |
item = obj[stuff] |
| 23 |
elif isinstance(obj, (list, tuple)): |
| 24 |
item = stuff |
| 25 |
else: |
| 26 |
item = getattr(obj, stuff) |
| 27 |
if types: |
| 28 |
match = False |
| 29 |
for type_ in types: |
| 30 |
if isinstance(item, type_): |
| 31 |
match = True |
| 32 |
break |
| 33 |
if not match: |
| 34 |
continue |
| 35 |
stream.write( |
| 36 |
(" " * level) |
| 37 |
+ (((repr(stuff) if level else stuff) + ": ") if item is not stuff else "") |
| 38 |
) |
| 39 |
if isinstance(item, (str, int, float)): |
| 40 |
# if isinstance(item, (str, unicode)) and "\n" in item: |
| 41 |
# stream.write('"""' + item + '"""' + ("," if level else "") + '\n') |
| 42 |
# else: |
| 43 |
stream.write(repr(item) + ("," if level else "") + "\n") |
| 44 |
elif isinstance(item, (dict, list, tuple)): |
| 45 |
if len((" " * level) + repr(item)) < 80: |
| 46 |
stream.write(repr(item) + ("," if level else "") + "\n") |
| 47 |
else: |
| 48 |
# stream.write(brackets[item.__class__][0] + '\n') |
| 49 |
ppdir(item, types, level=level + 1, stream=stream) |
| 50 |
# stream.write((" " * level) + brackets[item.__class__][1] + ("," if level else "") + '\n') |
| 51 |
else: |
| 52 |
stream.write(repr(item) + ("," if level else "") + "\n") |
| 53 |
if isinstance(obj, (dict, list, tuple)): |
| 54 |
stream.write( |
| 55 |
(" " * (level - 1)) |
| 56 |
+ brackets[class_][1] |
| 57 |
+ ("," if level - 1 else "") |
| 58 |
+ "\n" |
| 59 |
) |
| 60 |
bag = obj |