Skip to content

Commit 025e7d2

Browse files
authored
gh-113329: Catch OSError in doctest finder and document that inspect.getsourcefile/getfile can raise OSError (GH-113335)
Fixes #113329, which occurs when running doctests in a class docstring in a REPL environment. Since Python 3.10, an OSError is raised when the class source code cannot be found.
1 parent a2104b7 commit 025e7d2

3 files changed

Lines changed: 7 additions & 4 deletions

File tree

Doc/library/inspect.rst

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,7 @@ Retrieving source code
747747
.. function:: getfile(object)
748748

749749
Return the name of the (text or binary) file in which an object was defined.
750+
An :exc:`OSError` is raised if the source code cannot be retrieved.
750751
This will fail with a :exc:`TypeError` if the object is a built-in module,
751752
class, or function.
752753

@@ -760,9 +761,10 @@ Retrieving source code
760761
.. function:: getsourcefile(object)
761762

762763
Return the name of the Python source file in which an object was defined
763-
or ``None`` if no way can be identified to get the source. This
764-
will fail with a :exc:`TypeError` if the object is a built-in module, class, or
765-
function.
764+
or ``None`` if no way can be identified to get the source. An :exc:`OSError` is
765+
raised if the source code cannot be retrieved.
766+
This will fail with a :exc:`TypeError` if the object is a built-in module,
767+
class, or function.
766768

767769

768770
.. function:: getsourcelines(object)

Lib/doctest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -922,7 +922,7 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
922922
# given object's docstring.
923923
try:
924924
file = inspect.getsourcefile(obj)
925-
except TypeError:
925+
except (TypeError, OSError):
926926
source_lines = None
927927
else:
928928
if not file:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :exc:`OSError` being raised when trying to run doctests on a class objects in the REPL. Patch by Sten Wessel.

0 commit comments

Comments
 (0)