bpo-33826: add __filename__ to Python-defined classes for introspection by t-vi · Pull Request #13894 · python/cpython
So a year passed, I sent the following to python-dev, but I'm not sure whether it is filtered (it doesn't show up in the archives).
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 this PR in github and sent a bug and patch earlier 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.