Q:

Python - early return from exec

I know that some consider Python's exec and eval functions evil. I do not mind. I have different problem. Suppose that I have a script stored in a string and I want to execute it using function exec(my_script_as_string). Suppose that at some point in the script, e.g. based on certain condition I need to return from that script. How to do that? Command return is not for this for sure. Function quit() not only quits the script inside my exec() but also the outer script that called the exec. sys.exit is the same. So... how to do this? Is is even possible?
Example, which does not work:
print('A')
exec("print('B');quit();print('C')")
print('D')

My desired output would be:
A
B
D

but it is
A
B

I know that the script could always be rearranged so that there are many if/else clauses that will problably eliminate the need to exit early, but sometimes it is quite complicated especially when combined with cycles...

A:

One option would be to create a function within the exec that you then call, that way you could use return, for example:
exec("""
def _f():
    print('B')
    return
    print('C')
_f()
""")

