apply emulation patches only for a specific context

    :param module_names: var-args for the modules to patch, as in :func:`patch`
    :param local:
        if True, unpatching is done on every switch-out, and re-patching on
        every switch-in, so that they are only applied for the one coroutine

    :returns:
        a contextmanager that patches on ``__enter__`` and unpatches on
        ``__exit__``

def patched_context(*module_names, **kwargs):
    """apply emulation patches only for a specific context

    :param module_names: var-args for the modules to patch, as in :func:`patch`
    :param local:
        if True, unpatching is done on every switch-out, and re-patching on
        every switch-in, so that they are only applied for the one coroutine

    :returns:
        a contextmanager that patches on ``__enter__`` and unpatches on
        ``__exit__``
    """
    local = kwargs.pop('local', False)
    if kwargs:
        raise TypeError("patched_context() got an unexpected keyword " +
                        "argument %r" % kwargs.keys()[0])

    patch(*module_names)
    if local:
        @scheduler.local_incoming_hook
        @scheduler.local_outgoing_hook
        def hook(direction, target):
            {1: patch, 2: unpatch}[direction](*module_names)

    yield

    unpatch(*module_names)
    if local:
        scheduler.remove_local_incoming_hook(hook)
        scheduler.remove_local_outgoing_hook(hook)