From a0376c41022f111f9e826368716fab599144b61f 2018-05-30 13:03:15 From: Min RK Date: 2018-05-30 13:03:15 Subject: [PATCH] pretty-rendering for os.environ by default it's dict-like, but not a dict so doesn't get caught by the default dict printer --- diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index 6345d6d..aeaed92 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -77,11 +77,13 @@ Inheritance diagram: Portions (c) 2009 by Robert Kern. :license: BSD License. """ + from contextlib import contextmanager +import datetime +import os +import re import sys import types -import re -import datetime from collections import deque from io import StringIO from warnings import warn @@ -742,7 +744,6 @@ _type_pprinters = { tuple: _seq_pprinter_factory('(', ')'), list: _seq_pprinter_factory('[', ']'), dict: _dict_pprinter_factory('{', '}'), - set: _set_pprinter_factory('{', '}'), frozenset: _set_pprinter_factory('frozenset({', '})'), super: _super_pprint, @@ -751,12 +752,17 @@ _type_pprinters = { types.FunctionType: _function_pprint, types.BuiltinFunctionType: _function_pprint, types.MethodType: _repr_pprint, - datetime.datetime: _repr_pprint, datetime.timedelta: _repr_pprint, _exception_base: _exception_pprint } +# render os.environ like a dict +_env_type = type(os.environ) +# future-proof in case os.environ becomes a plain dict? +if _env_type is not dict: + _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}') + try: # In PyPy, types.DictProxyType is dict, setting the dictproxy printer # using dict.setdefault avoids overwritting the dict printer @@ -768,7 +774,7 @@ except AttributeError: # Python 3 _type_pprinters[types.MappingProxyType] = \ _dict_pprinter_factory('mappingproxy({', '})') _type_pprinters[slice] = _repr_pprint - + try: _type_pprinters[long] = _repr_pprint _type_pprinters[unicode] = _repr_pprint diff --git a/IPython/lib/tests/test_pretty.py b/IPython/lib/tests/test_pretty.py index 68e90ec..d1c470b 100644 --- a/IPython/lib/tests/test_pretty.py +++ b/IPython/lib/tests/test_pretty.py @@ -6,6 +6,7 @@ from collections import Counter, defaultdict, deque, OrderedDict +import os import types import string import unittest @@ -406,6 +407,15 @@ def test_mappingproxy(): for obj, expected in cases: nt.assert_equal(pretty.pretty(obj), expected) + +def test_pretty_environ(): + dict_repr = pretty.pretty(dict(os.environ)) + # reindent to align with 'environ' prefix + dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ'))) + env_repr = pretty.pretty(os.environ) + nt.assert_equals(env_repr, 'environ' + dict_indented) + + def test_function_pretty(): "Test pretty print of function" # posixpath is a pure python module, its interface is consistent