homepage

This issue tracker has been migrated to GitHub , and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: inspect.getsource returns wrong class definition when multiple class definitions share the same name (but are defined in different scopes)
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: inspect.getsource returns incorrect source for classes when class definition is part of multiline strings
View: 35113
Assigned To: Nosy List: donovick, lennyt, serhiy.storchaka, xtreak
Priority: normal Keywords:

Created on 2019年08月22日 22:46 by lennyt, last changed 2022年04月11日 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
inspect-getsource-issue.py lennyt, 2019年08月22日 22:46 Code to reproduce the issue
Messages (5)
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
print(inspect.getsource(foo1()))
print(foo1().x)
print(foo0().x)
```
Running this file produces
```
❯ python inspect-getsource-issue.py
 class Foo:
 x = 4
5
4
```
msg350236 - (view) Author: Leonard Truong (lennyt) Date: 2019年08月22日 22:49
Turns out this is a documented issue in the source code: https://github.com/python/cpython/blob/3.7/Lib/inspect.py#L794-L796 
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 committer) Date: 2019年08月23日 02:14
This looks like a duplicate of https://bugs.python.org/issue35113 . I have created a PR for the issue but didn't have time to debug the Windows issue.
msg355307 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019年10月24日 09:13
Closing it as duplicate of issue35113.
History
Date User Action Args
2022年04月11日 14:59:19adminsetgithub: 82103
2019年10月24日 09:13:41xtreaksetstatus: open -> closed

superseder: inspect.getsource returns incorrect source for classes when class definition is part of multiline strings
nosy: + serhiy.storchaka

messages: + msg355307
type: behavior
resolution: duplicate
stage: resolved
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

AltStyle によって変換されたページ (->オリジナル) /