[Python-checkins] gh-102541: Fix Helper.help("mod") for non-existent mod (#105934)

terryjreedy webhook-mailer at python.org
Sat Jul 1 18:46:10 EDT 2023


https://github.com/python/cpython/commit/0530f4f64629ff97f3feb7524da0833b9535e8b6
commit: 0530f4f64629ff97f3feb7524da0833b9535e8b6
branch: main
author: Kirill Podoprigora <kirill.bast9 at mail.ru>
committer: terryjreedy <tjreedy at udel.edu>
date: 2023-07-01T18:46:06-04:00
summary:

gh-102541: Fix Helper.help("mod") for non-existent mod (#105934)

If the output arg to Helper() is a stream rather than the default None, which means 'page to stdout', the ImportError from pydoc.resolve is currently not caught in pydoc.doc. The same error is caught when output is None.
---------

Co-authored-by: Terry Jan Reedy <tjreedy at udel.edu>

files:
A Misc/NEWS.d/next/Library/2023-07-01-16-40-54.gh-issue-102541.C1ahtk.rst
M Lib/pydoc.py
M Lib/test/test_pydoc.py

diff --git a/Lib/pydoc.py b/Lib/pydoc.py
index d69369d4196ea..185f09e603df2 100755
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -1790,7 +1790,11 @@ def doc(thing, title='Python Library Documentation: %s', forceload=0,
                 raise
             print(exc)
     else:
-        output.write(render_doc(thing, title, forceload, plaintext))
+        try:
+            s = render_doc(thing, title, forceload, plaintext)
+        except ImportError as exc:
+            s = str(exc)
+        output.write(s)
 
 def writedoc(thing, forceload=0):
     """Write HTML documentation to a file in the current directory."""
diff --git a/Lib/test/test_pydoc.py b/Lib/test/test_pydoc.py
index cefc71cb5a7f5..115ffd3c29d4d 100644
--- a/Lib/test/test_pydoc.py
+++ b/Lib/test/test_pydoc.py
@@ -631,6 +631,13 @@ def test_builtin_on_metaclasses(self):
         # Testing that the subclasses section does not appear
         self.assertNotIn('Built-in subclasses', text)
 
+    def test_fail_help_output_redirect(self):
+        with StringIO() as buf:
+            helper = pydoc.Helper(output=buf)
+            helper.help("abd")
+            expected = missing_pattern % "abd"
+            self.assertEqual(expected, buf.getvalue().strip().replace('\n', os.linesep))
+
     @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                      'trace function introduces __locals__ unexpectedly')
     @requires_docstrings
diff --git a/Misc/NEWS.d/next/Library/2023-07-01-16-40-54.gh-issue-102541.C1ahtk.rst b/Misc/NEWS.d/next/Library/2023-07-01-16-40-54.gh-issue-102541.C1ahtk.rst
new file mode 100644
index 0000000000000..efaf5db10f3e1
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-07-01-16-40-54.gh-issue-102541.C1ahtk.rst
@@ -0,0 +1 @@
+Make pydoc.doc catch bad module ImportError when output stream is not None.



More information about the Python-checkins mailing list