diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index 3115d3f..1cb46b1 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -648,6 +648,22 @@ def _re_pattern_pprint(obj, p, cycle): p.text(')') +def _types_simplenamespace_pprint(obj, p, cycle): + """The pprint function for types.SimpleNamespace.""" + name = 'namespace' + with p.group(len(name) + 1, name + '(', ')'): + if cycle: + p.text('...') + else: + for idx, (attr, value) in enumerate(obj.__dict__.items()): + if idx: + p.text(',') + p.breakable() + attr_kwarg = '{}='.format(attr) + with p.group(len(attr_kwarg), attr_kwarg): + p.pretty(value) + + def _type_pprint(obj, p, cycle): """The pprint for classes and types.""" # Heap allocated types might not have the module attribute, @@ -741,6 +757,7 @@ _type_pprinters = { types.FunctionType: _function_pprint, types.BuiltinFunctionType: _function_pprint, types.MethodType: _repr_pprint, + types.SimpleNamespace: _types_simplenamespace_pprint, datetime.datetime: _repr_pprint, datetime.timedelta: _repr_pprint, _exception_base: _exception_pprint diff --git a/IPython/lib/tests/test_pretty.py b/IPython/lib/tests/test_pretty.py index 695012d..ba4c329 100644 --- a/IPython/lib/tests/test_pretty.py +++ b/IPython/lib/tests/test_pretty.py @@ -407,6 +407,26 @@ def test_mappingproxy(): nt.assert_equal(pretty.pretty(obj), expected) +def test_simplenamespace(): + SN = types.SimpleNamespace + + sn_recursive = SN() + sn_recursive.first = sn_recursive + sn_recursive.second = sn_recursive + cases = [ + (SN(), "namespace()"), + (SN(x=SN()), "namespace(x=namespace())"), + (SN(a_long_name=[SN(s=string.ascii_lowercase)]*3, a_short_name=None), + "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n" + " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n" + " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n" + " a_short_name=None)"), + (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"), + ] + 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