inspect.stack(0) can be faster than inspect.stack() . However, this is the fastest way to not invoke it at all, and perhaps use a template instead, for example:
frame = inspect.currentframe() while frame: if has_what_i_want(frame):
Note that the last frame.f_back is None , and the loop ends.
sys._getframe(1) will obviously not be used because it is an internal method.
Alternatively, inspect.getouterframes(inspect.currentframe()) can be looped, but it is expected to be slower than the approach described above.
source share