Skip to content

Commit 4fe5490

Browse files
[3.13] gh-113329: Catch OSError in doctest finder and document that inspect.getsourcefile/getfile can raise OSError (GH-113335) (GH-155660)
Fixes GH-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. (cherry picked from commit 025e7d2) Co-authored-by: Sten Wessel <sten@stenwessel.nl>
1 parent 761af88 commit 4fe5490

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
@@ -634,6 +634,7 @@ Retrieving source code
634634
.. function:: getfile(object)
635635

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

@@ -647,9 +648,10 @@ Retrieving source code
647648
.. function:: getsourcefile(object)
648649

649650
Return the name of the Python source file in which an object was defined
650-
or ``None`` if no way can be identified to get the source. This
651-
will fail with a :exc:`TypeError` if the object is a built-in module, class, or
652-
function.
651+
or ``None`` if no way can be identified to get the source. An :exc:`OSError` is
652+
raised if the source code cannot be retrieved.
653+
This will fail with a :exc:`TypeError` if the object is a built-in module,
654+
class, or function.
653655

654656

655657
.. function:: getsourcelines(object)

Lib/doctest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,7 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
926926
# given object's docstring.
927927
try:
928928
file = inspect.getsourcefile(obj)
929-
except TypeError:
929+
except (TypeError, OSError):
930930
source_lines = None
931931
else:
932932
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)