[Python-checkins] bpo-40108: Improve the error message in runpy when importing a module that includes the extension (GH-19239)

Pablo Galindo webhook-mailer at python.org
Tue Mar 31 07:24:07 EDT 2020


https://github.com/python/cpython/commit/ef67512b40240f765026ad41d60b0c9a6dacd2b9
commit: ef67512b40240f765026ad41d60b0c9a6dacd2b9
branch: master
author: Pablo Galindo <Pablogsal at gmail.com>
committer: GitHub <noreply at github.com>
date: 2020-03-31T12:23:55+01:00
summary:

bpo-40108: Improve the error message in runpy when importing a module that includes the extension (GH-19239)

files:
A Misc/NEWS.d/next/Library/2020-03-31-01-11-20.bpo-40108.EGDVQ_.rst
M Lib/runpy.py
M Lib/test/test_cmd_line_script.py

diff --git a/Lib/runpy.py b/Lib/runpy.py
index 0f54f3e71b6fe..7e1e1ac5dde2d 100644
--- a/Lib/runpy.py
+++ b/Lib/runpy.py
@@ -133,6 +133,9 @@ def _get_module_details(mod_name, error=ImportError):
         # importlib, where the latter raises other errors for cases where
         # pkgutil previously raised ImportError
         msg = "Error while finding module specification for {!r} ({}: {})"
+        if mod_name.endswith(".py"):
+            msg += (f". Try using '{mod_name[:-3]}' instead of "
+                    f"'{mod_name}' as the module name.")
         raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
     if spec is None:
         raise error("No module named %s" % mod_name)
diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py
index adfb8ce5ed245..44a5487d75dff 100644
--- a/Lib/test/test_cmd_line_script.py
+++ b/Lib/test/test_cmd_line_script.py
@@ -499,6 +499,16 @@ def test_dash_m_bad_pyc(self):
             self.assertNotIn(b'is a package', err)
             self.assertNotIn(b'Traceback', err)
 
+    def test_hint_when_triying_to_import_a_py_file(self):
+        with support.temp_dir() as script_dir, \
+                support.change_cwd(path=script_dir):
+            # Create invalid *.pyc as empty file
+            with open('asyncio.py', 'wb'):
+                pass
+            err = self.check_dash_m_failure('asyncio.py')
+            self.assertIn(b"Try using 'asyncio' instead "
+                          b"of 'asyncio.py' as the module name", err)
+
     def test_dash_m_init_traceback(self):
         # These were wrapped in an ImportError and tracebacks were
         # suppressed; see Issue 14285
diff --git a/Misc/NEWS.d/next/Library/2020-03-31-01-11-20.bpo-40108.EGDVQ_.rst b/Misc/NEWS.d/next/Library/2020-03-31-01-11-20.bpo-40108.EGDVQ_.rst
new file mode 100644
index 0000000000000..778a0f1b1a596
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-03-31-01-11-20.bpo-40108.EGDVQ_.rst
@@ -0,0 +1,3 @@
+Improve the error message when triying to import a module using :mod:`runpy`
+and incorrently use the ".py" extension at the end of the module name. Patch
+by Pablo Galindo.



More information about the Python-checkins mailing list