import os
from contextlib import contextmanager


@contextmanager
def effective_user(uid, gid):
    """
    A ContextManager that executes code in the with block with effective uid / gid given
    """
    original_uid = os.geteuid()
    original_gid = os.getegid()
    os.setegid(gid)
    os.seteuid(uid)
    yield
    os.setegid(original_gid)
    os.setuid(original_uid)

@@ -306,14 +306,44 @@
     
-yield%0A
+try:%0A        yield%0A    finally:%0A    
     
@@ -363,24 +363,28 @@
 iginal_gid)%0A
+    
     os.setui

Make effective_user handle exceptions properly