On 18.02.2020 08:33, Serhiy Storchaka wrote:
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?
This sounds like a nice idea, but it may make sense to limit the frame to one already on the stack. Otherwise, the code you're executing may never return to your current stack... OTOH, perhaps that could be regarded and used as a feature, similar to what PyPy exposes: https://doc.pypy.org/en/latest/stackless.html -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Feb 18 2020)
Python Projects, Coaching and Support ... https://www.egenix.com/ Python Product Development ... https://consulting.egenix.com/
::: We implement business ideas - efficiently in both time and costs ::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 https://www.egenix.com/company/contact/ https://www.malemburg.com/