Handling signals in Python inside a function
What about implementing your signal handling code inside a class? This could look something like the following:

class GracefulExit:
    def __enter__(self):
        # set up signals here
        # store old signal handlers as instance variables

    def __exit__(self, type, value, traceback):
        # restore old signal handlers


You can then use this in your code as follows:

with GracefulExit():
    # Signals will be caught inside this block.

# Signals will no more be caught here.


You'll find more examples of how to use the with-statement on the web.