guppylang icon indicating copy to clipboard operation
guppylang copied to clipboard

`inspect.getsource` produces incorrect results for redefined classes

Open mark-koch opened this issue 1 year ago • 2 comments

class Test:
    pass

class Test:
    x: int

print(inspect.getsource(Test))  # Prints the *first* definition of Test

This is because inspect._ClassFinder looks through the AST and stops once it finds the first class matching the name:

https://github.com/python/cpython/blob/c3a866c91585b7dbd5e8c3d4737dc9c1e04ee8de/Lib/inspect.py#L1039-L1067

mark-koch avatar Sep 05 '24 12:09 mark-koch

class Test:
    pass

class Test:
    x: int

@mark-koch Is this even valid code? Certainly not desirable. Shouldn't we just disallow a second definition of the class?

qartik avatar Sep 05 '24 14:09 qartik

We used to disallow it, but that lead to problems in Jupyter notebooks were you might want to run a cell multiple times with updated contents.

Now we try to match Python where you can just redefine objects and the old stuff goes out of scope

mark-koch avatar Sep 05 '24 15:09 mark-koch

Fixed by #1108

mark-koch avatar Jul 22 '25 12:07 mark-koch