try/except/finally

Joshua Landau joshua at landau.ws
Sun Jun 8 14:05:01 EDT 2014


On 6 June 2014 18:39, Roy Smith <roy at panix.com> wrote:
>
> The only way I can think of to bypass a finally block would be to call
> os._exit(), or send yourself a kill signal.

If you're willing to use implementation details...

---

# BreakN.py

import sys

# Turn tracing on if it is off
if sys.gettrace() is None: sys.settrace(lambda frame, event, arg: None)

def break_n(n):
    frame = sys._getframe().f_back

    for _ in range(n):
        frame.f_trace = skip_function_tracer
        frame = frame.f_back

def skip_function_tracer(frame, event, arg):
    try:
        # Skip this line
        while True:
            frame.f_lineno += 1

    except ValueError as e:
        # Finished tracing function; remove trace
        pass

---

# Thing_you_run.py

from BreakN import break_n

def foo():
    try:
        print("I am not skipped")
        break_n(1)
        print("I am skipped")
        ...
    finally:
        print("I am skipped")
        ...

foo()
#>>> I am not skipped



More information about the Python-list mailing list