Skip to content

Commit ed58355

Browse files
[3.14] gh-113329: Catch OSError in doctest finder and document that inspect.getsourcefile/getfile can raise OSError (GH-113335) (GH-155659)
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 8b67308 commit ed58355

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
@@ -714,6 +714,7 @@ Retrieving source code
714714
.. function:: getfile(object)
715715

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

@@ -727,9 +728,10 @@ Retrieving source code
727728
.. function:: getsourcefile(object)
728729

729730
Return the name of the Python source file in which an object was defined
730-
or ``None`` if no way can be identified to get the source. This
731-
will fail with a :exc:`TypeError` if the object is a built-in module, class, or
732-
function.
731+
or ``None`` if no way can be identified to get the source. An :exc:`OSError` is
732+
raised if the source code cannot be retrieved.
733+
This will fail with a :exc:`TypeError` if the object is a built-in module,
734+
class, or function.
733735

734736

735737
.. function:: getsourcelines(object)

Lib/doctest.py

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