]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-106727: Add `__module__` check for `inspect.getsource(cls)` (#106968)
authorTian Gao <gaogaotiantian@hotmail.com>
Mon, 24 Jul 2023 20:12:45 +0000 (12:12 -0800)
committerGitHub <noreply@github.com>
Mon, 24 Jul 2023 20:12:45 +0000 (13:12 -0700)
Lib/inspect.py
Lib/test/test_inspect.py

index 675714dc8b3f7053c4523e9832d84d242fd0b468..c8211833dd0831962f1f69e92b6b9efdc1a63d1f 100644 (file)
@@ -1078,7 +1078,8 @@ class _ClassFinder(ast.NodeVisitor):
 
             # First, let's see if there are any method definitions
             for member in self.cls.__dict__.values():
-                if isinstance(member, types.FunctionType):
+                if (isinstance(member, types.FunctionType) and
+                    member.__module__ == self.cls.__module__):
                     for lineno, end_lineno in self.lineno_found:
                         if lineno <= member.__code__.co_firstlineno <= end_lineno:
                             return lineno
index 33a593f3591d68ab54bdefb87dda8a4e40a0082d..3fbfc073255532c8847cb02697fad6ff5228766d 100644 (file)
@@ -15,6 +15,7 @@ import pickle
 import shutil
 import sys
 import types
+import tempfile
 import textwrap
 import unicodedata
 import unittest
@@ -963,6 +964,33 @@ class TestBuggyCases(GetSourceBase):
         self.assertSourceEqual(mod2.cls213, 218, 222)
         self.assertSourceEqual(mod2.cls213().func219(), 220, 221)
 
+    def test_class_with_method_from_other_module(self):
+        with tempfile.TemporaryDirectory() as tempdir:
+            with open(os.path.join(tempdir, 'inspect_actual%spy' % os.extsep),
+                      'w', encoding='utf-8') as f:
+                f.write(textwrap.dedent("""
+                    import inspect_other
+                    class A:
+                        def f(self):
+                            pass
+                    class A:
+                        def f(self):
+                            pass  # correct one
+                    A.f = inspect_other.A.f
+                    """))
+
+            with open(os.path.join(tempdir, 'inspect_other%spy' % os.extsep),
+                      'w', encoding='utf-8') as f:
+                f.write(textwrap.dedent("""
+                    class A:
+                        def f(self):
+                            pass
+                    """))
+
+            with DirsOnSysPath(tempdir):
+                import inspect_actual
+                self.assertIn("correct", inspect.getsource(inspect_actual.A))
+
     @unittest.skipIf(
         support.is_emscripten or support.is_wasi,
         "socket.accept is broken"