Hello,
thank you for making Python and the neat inspect module.
I would love to hear your opinion on the following aspect of inspect
that I believe might be worth improving:
Consider the following program saved in a file (say hello.py):
import inspect
def hello():
print("Hello World")
print(inspect.getsource(hello))
class Hello:
def __init__(self):
print("Hello World")
print(inspect.getsource(Hello))
Running hello.py will, unsurprisingly, print the source of hello and Hello.
Now, some of us use an Jupyter (with the capabilities provided by
IPython) notebooks, which are a great tool and awesome match with
Python. These notebooks can be large and complex enough to want to use
introspection on methods defined in itself (also, I'm prototyping things
I might want to use as a library in Notebooks a lot, and I think I'm not
alone).
IPython enhances the interactive console to enable introspection (by
providing "files" for the cells).
As a result, the following will work as expected:
def hello():
print("Hello World")
print(inspect.getsource(hello))
However, it does not work for classes:
class Hello:
def __init__(self):
print("Hello World")
print(inspect.getsource(Hello))
will run into an error in a Jupyter notebook, more precisely
TypeError: <class '__main__.Hello'> is a built-in class
The reason why the latter does not work is because inspect cannot find a
source file.
The technical background is that for a function hello, inspect.getfile
finds the file through hello.__code__.co_filename
which IPython can arrange for, while for the class Hello, it tries
`Hello.__module__`, which is `__main__` and then would see if
sys.modules[Hello.__module__] has a __file__ attribute, which it does
not (and which could not be disambiguated into cell-level).
I once made a PR in github #13894 and earlier
https://bugs.python.org/issue33826 but got, let's say, reactions that
were not entirely encouraging. I still think that it is a useful feature
and I don't think that there are readily available solutions and after
another year has passed, I humbly submit this for your considerations.
Best regards and thank you.
Thomas
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/AC5B5VORS6FF6KJ3EG5DIV3ZLAQB6DIY/
Code of Conduct: http://python.org/psf/codeofconduct/