On 2020-06-17 09:02, Serhiy Storchaka wrote:
16.06.20 21:02, Guido van Rossum пише:
It would certainly be much easier to get through the review process.
Adding a `__filename__` (why not `__file__`?) attribute to classes is
a major surgery, presumably requiring a PEP, and debating the pros and
cons and performance implications and fixing a bunch of tests that
don't expect this attribute, and so on. Adding an imperfect solution
to inspect.getsource() would only require the cooperation of whoever
maintains the inspect module.
If add the file name of the sources as a class attribute, we need also
to add the line number (or the range of line numbers) of the class
definition. Otherwise inspect.getsource() will still be ambiguous.
That, or even the entire __code__ of the internal function that sets up
the class. That has all the needed information.
I did a small experiment with this, and indeed it breaks tests that
either don't expect the attribute or expect anything with __code__ is a
function:
https://github.com/python/cpython/commit/3fddc0906f2e7b92ea0f7ff040560a10372f91ec
You can actually do this in pure Python, just to see what breaks. See
the attachment.
Also,
specifying the file name does not help in case of REPL or compiling a
string, so maybe you need to attach full source text to a class?
You get the same problem with functions, already. But Jupyter Notebook
apparently works around this issue.
import builtins
orig_build_class = builtins.__build_class__
def build_class(func, *args, **kwds):
result = orig_build_class(func, *args, **kwds)
result.__code__ = func.__code__
return result
builtins.__build_class__ = build_class
##############
# Demo:
import inspect
class C():
def hello(self):
print('Hello world!')
print(inspect.getsource(C))
_______________________________________________
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/Q3EZXN6KLA6WPWEN5HV3T5NGC5PMFB62/
Code of Conduct: http://python.org/psf/codeofconduct/