Skip to content

Commit b383703

Browse files
gh-106727: Add __module__ check for inspect.getsource(cls) (#106968)
1 parent 8ebc9fc commit b383703

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

Lib/inspect.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1078,7 +1078,8 @@ def get_lineno(self):
10781078

10791079
# First, let's see if there are any method definitions
10801080
for member in self.cls.__dict__.values():
1081-
if isinstance(member, types.FunctionType):
1081+
if (isinstance(member, types.FunctionType) and
1082+
member.__module__ == self.cls.__module__):
10821083
for lineno, end_lineno in self.lineno_found:
10831084
if lineno <= member.__code__.co_firstlineno <= end_lineno:
10841085
return lineno

Lib/test/test_inspect.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import shutil
1616
import sys
1717
import types
18+
import tempfile
1819
import textwrap
1920
import unicodedata
2021
import unittest
@@ -963,6 +964,33 @@ def test_nested_class_definition_inside_function(self):
963964
self.assertSourceEqual(mod2.cls213, 218, 222)
964965
self.assertSourceEqual(mod2.cls213().func219(), 220, 221)
965966

967+
def test_class_with_method_from_other_module(self):
968+
with tempfile.TemporaryDirectory() as tempdir:
969+
with open(os.path.join(tempdir, 'inspect_actual%spy' % os.extsep),
970+
'w', encoding='utf-8') as f:
971+
f.write(textwrap.dedent("""
972+
import inspect_other
973+
class A:
974+
def f(self):
975+
pass
976+
class A:
977+
def f(self):
978+
pass # correct one
979+
A.f = inspect_other.A.f
980+
"""))
981+
982+
with open(os.path.join(tempdir, 'inspect_other%spy' % os.extsep),
983+
'w', encoding='utf-8') as f:
984+
f.write(textwrap.dedent("""
985+
class A:
986+
def f(self):
987+
pass
988+
"""))
989+
990+
with DirsOnSysPath(tempdir):
991+
import inspect_actual
992+
self.assertIn("correct", inspect.getsource(inspect_actual.A))
993+
966994
@unittest.skipIf(
967995
support.is_emscripten or support.is_wasi,
968996
"socket.accept is broken"

0 commit comments

Comments
 (0)