[Python-checkins] bpo-37376: pprint support for SimpleNamespace (GH-14318)

Miss Islington (bot) webhook-mailer at python.org
Wed Jun 26 19:13:32 EDT 2019


https://github.com/python/cpython/commit/06a8916cf465f139dca958685b0da899364b8a8c
commit: 06a8916cf465f139dca958685b0da899364b8a8c
branch: master
author: Carl Bordum Hansen <carl at bordum.dk>
committer: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
date: 2019-06-26T16:13:18-07:00
summary:

bpo-37376: pprint support for SimpleNamespace (GH-14318)



https://bugs.python.org/issue37376

files:
A Misc/NEWS.d/next/Library/2019-06-24-11-26-34.bpo-37376.SwSUQ4.rst
M Doc/library/pprint.rst
M Doc/whatsnew/3.9.rst
M Lib/pprint.py
M Lib/test/test_pprint.py
M Misc/ACKS

diff --git a/Doc/library/pprint.rst b/Doc/library/pprint.rst
index 9abf2865ef61..207c3f8bca92 100644
--- a/Doc/library/pprint.rst
+++ b/Doc/library/pprint.rst
@@ -25,6 +25,9 @@ width constraint.
 
 Dictionaries are sorted by key before the display is computed.
 
+.. versionchanged:: 3.9
+   Added support for pretty-printing :class:`types.SimpleNamespace`.
+
 The :mod:`pprint` module defines one class:
 
 .. First the implementation class:
diff --git a/Doc/whatsnew/3.9.rst b/Doc/whatsnew/3.9.rst
index 780c0a94d65c..379a097ada15 100644
--- a/Doc/whatsnew/3.9.rst
+++ b/Doc/whatsnew/3.9.rst
@@ -111,6 +111,12 @@ threads were never supported in subinterpreters. Previously, the subinterpreter
 finalization crashed with a Pyton fatal error if a daemon thread was still
 running.
 
+pprint
+------
+
+:mod:`pprint` can now pretty-print :class:`types.SimpleNamespace`.
+(Contributed by Carl Bordum Hansen in :issue:`37376`.)
+
 
 Optimizations
 =============
diff --git a/Lib/pprint.py b/Lib/pprint.py
index 4bfcc31b25ea..7c1118a484b2 100644
--- a/Lib/pprint.py
+++ b/Lib/pprint.py
@@ -342,6 +342,33 @@ def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level
 
     _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
 
+    def _pprint_simplenamespace(self, object, stream, indent, allowance, context, level):
+        if type(object) is _types.SimpleNamespace:
+            # The SimpleNamespace repr is "namespace" instead of the class
+            # name, so we do the same here. For subclasses; use the class name.
+            cls_name = 'namespace'
+        else:
+            cls_name = object.__class__.__name__
+        indent += len(cls_name) + 1
+        delimnl = ',\n' + ' ' * indent
+        items = object.__dict__.items()
+        last_index = len(items) - 1
+
+        stream.write(cls_name + '(')
+        for i, (key, ent) in enumerate(items):
+            stream.write(key)
+            stream.write('=')
+
+            last = i == last_index
+            self._format(ent, stream, indent + len(key) + 1,
+                         allowance if last else 1,
+                         context, level)
+            if not last:
+                stream.write(delimnl)
+        stream.write(')')
+
+    _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
+
     def _format_dict_items(self, items, stream, indent, allowance, context,
                            level):
         write = stream.write
diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py
index 269ac0624eeb..b3b8715a5f75 100644
--- a/Lib/test/test_pprint.py
+++ b/Lib/test/test_pprint.py
@@ -346,6 +346,65 @@ def test_mapping_proxy(self):
                           ('lazy', 7),
                           ('dog', 8)]))""")
 
+    def test_empty_simple_namespace(self):
+        ns = types.SimpleNamespace()
+        formatted = pprint.pformat(ns)
+        self.assertEqual(formatted, "namespace()")
+
+    def test_small_simple_namespace(self):
+        ns = types.SimpleNamespace(a=1, b=2)
+        formatted = pprint.pformat(ns)
+        self.assertEqual(formatted, "namespace(a=1, b=2)")
+
+    def test_simple_namespace(self):
+        ns = types.SimpleNamespace(
+            the=0,
+            quick=1,
+            brown=2,
+            fox=3,
+            jumped=4,
+            over=5,
+            a=6,
+            lazy=7,
+            dog=8,
+        )
+        formatted = pprint.pformat(ns, width=60)
+        self.assertEqual(formatted, """\
+namespace(the=0,
+          quick=1,
+          brown=2,
+          fox=3,
+          jumped=4,
+          over=5,
+          a=6,
+          lazy=7,
+          dog=8)""")
+
+    def test_simple_namespace_subclass(self):
+        class AdvancedNamespace(types.SimpleNamespace): pass
+        ns = AdvancedNamespace(
+            the=0,
+            quick=1,
+            brown=2,
+            fox=3,
+            jumped=4,
+            over=5,
+            a=6,
+            lazy=7,
+            dog=8,
+        )
+        formatted = pprint.pformat(ns, width=60)
+        self.assertEqual(formatted, """\
+AdvancedNamespace(the=0,
+                  quick=1,
+                  brown=2,
+                  fox=3,
+                  jumped=4,
+                  over=5,
+                  a=6,
+                  lazy=7,
+                  dog=8)""")
+
     def test_subclassing(self):
         o = {'names with spaces': 'should be presented using repr()',
              'others.should.not.be': 'like.this'}
diff --git a/Misc/ACKS b/Misc/ACKS
index 05a3e61f6941..df0810fff46c 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -628,6 +628,7 @@ Mark Hammond
 Harald Hanche-Olsen
 Manus Hand
 Milton L. Hankins
+Carl Bordum Hansen
 Stephen Hansen
 Barry Hantman
 Lynda Hardman
diff --git a/Misc/NEWS.d/next/Library/2019-06-24-11-26-34.bpo-37376.SwSUQ4.rst b/Misc/NEWS.d/next/Library/2019-06-24-11-26-34.bpo-37376.SwSUQ4.rst
new file mode 100644
index 000000000000..f47d8130f6ec
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-06-24-11-26-34.bpo-37376.SwSUQ4.rst
@@ -0,0 +1,2 @@
+:mod:`pprint` now has support for :class:`types.SimpleNamespace`. Patch by Carl
+Bordum Hansen.



More information about the Python-checkins mailing list