The idea is inspired by the following StackOverflow question: https://stackoverflow.com/questions/40945752/inspect-who-imported-me and the corresponding BPO issue: https://bugs.python.org/issue39643.

In the older Python versions the f_back attribute of the frame in which the module code is executed pointed to the frame which executes the import statement or calls __import__() or import_module(). But after rewriting the import machinery in Python, there are other frames between the caller frame and the calling frame. This caused problems with tracebacks which was worked around by removing intermediate frames related to the import machinery when the exception floats to the caller. But there is still unresolved problem with warnings, and all frames of the import machinery are visible from the imported code.

I propose to add possibility to execute the code in the context of different frame. Either add a frame argument in exec() and eval(), which will allow to pass an arbitrary frame. Or add a stacklevel argument in exec() and eval() (similar to warnings.warn()), which will limit possible frames to the parent frames of the current frame. I do not know what is more feasible.

This will automatically fix problems with warnings. This will allow to get rid the workaround for exceptions, and may make the code simpler. This will allow the imported code to do miscellaneous magic things with the code which performs the import.

What do you think about this?
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ETBOLQKHTZFH7ELNOJG3TWRAXCOGYX2D/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to