Skip to content

Commit ea28747

Browse files
stenwesselmiss-islington
authored andcommitted
gh-113329: Catch OSError in doctest finder and document that inspect.getsourcefile/getfile can raise OSError (GH-113335)
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 ed38a08 commit ea28747

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
@@ -743,6 +743,7 @@ Retrieving source code
743743
.. function:: getfile(object)
744744

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

@@ -756,9 +757,10 @@ Retrieving source code
756757
.. function:: getsourcefile(object)
757758

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

763765

764766
.. 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)