Title: inspect.getsource returns wrong class definition when multiple class definitions share the same name (but are defined in different scopes)
Type: Stage:
Components: Library (Lib) Versions: Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: donovick, lennyt, xtreak
Priority: normal Keywords:

Created on 2019-08-22 22:46 by lennyt, last changed 2019-08-23 02:14 by xtreak.

File name Uploaded Description Edit lennyt, 2019-08-22 22:46 Code to reproduce the issue
Messages (4)
msg350235 - (view) Author: Leonard Truong (lennyt) Date: 2019-08-22 22:46
Here's a case where `inspect.getsource` returns the wrong class definition when a file contains multiple class definitions with the same name. This pattern is valid runtime behavior when the class definitions are inside different scopes (e.g. a factory pattern where classes are defined and returned inside a function).

import inspect

def foo0():
    class Foo:
        x = 4
    return Foo

def foo1():
    class Foo:
        x = 5
    return Foo



Running this file produces
❯ python
    class Foo:
        x = 4

msg350236 - (view) Author: Leonard Truong (lennyt) Date: 2019-08-22 22:49
Turns out this is a documented issue in the source code:
msg350241 - (view) Author: Caleb Donovick (donovick) * Date: 2019-08-22 23:21
I think findsource could be made more robust by using __qualname__ if it available.
msg350244 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python triager) Date: 2019-08-23 02:14
This looks like a duplicate of . I have created a PR for the issue but didn't have time to debug the Windows issue.
Date User Action Args
2019-08-23 02:14:06xtreaksetnosy: + xtreak
messages: + msg350244
2019-08-22 23:21:26donovicksetmessages: + msg350241
2019-08-22 23:09:01donovicksetnosy: + donovick
2019-08-22 22:49:08lennytsetmessages: + msg350236
2019-08-22 22:46:07lennytcreate