[issue44648] Inspect.getsource raises wrong error on classes in interactive session

Andrei Kulakov report at bugs.python.org
Fri Jul 16 10:55:37 EDT 2021


Andrei Kulakov <andrei.avk at gmail.com> added the comment:

Łukasz:

Thanks for looking at this!

 - I agree OSError is not ideal, but I chose it because it's consistent with how inspect reports similar errors. For example, see all instances of OSError, except for first, in this function:

https://github.com/python/cpython/blob/7915c96ffd7ddc5cb6d54015ee4c31255a416892/Lib/inspect.py#L930

I think it's an implementation detail that class source is not available on interactive prompt, for example function source is available via `inspect.getsource()`.

If a user can do getsource(func) and getsource(cls) in a file, and getsource(func) on interactive prompt, it seems wrong to return a ValueError when the user is trying to getsource(cls) in interactive.

I'm open to change it to ValueError though because I think the err message here is more important to avoid user confusion.

 - good point about __main__.py files, I didn't remember about them. However they will have the __file__ attribute set, so they will return that right above the check for '__main__' in my patch.

I tested it to make sure:
import inspect
class A: 0
print(inspect.getsource(A))


./python.exe ~/temp/__main__.py                                                 
class A: 0

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44648>
_______________________________________


More information about the Python-bugs-list mailing list