def patch_class(cls):
    """Class decorator for monkey patching.

    Decorating a class (patch) with @patch_class(orig) will change orig, so
    that every method defined in patch will call that implementation instead
    of the one in orig.

    The methods take the original (unbound) implementation as the
    second argument after self; the rest is passed as is.

    It's the responsibility of the wrapper method to call the original
    if appropriate, with arguments it wants (self probably being
    the first one).

    Methods without an implementation in the original are copied verbatim.
    """
    def _wrap_fun(wrapper, original):
        def wrapped(self, *args, **kwargs):
            return wrapper(self, original, *args, **kwargs)
        return wrapped
    def _wrap_cls(patch):
        for func in dir(patch):
            if not func.startswith('__'):
                wrapper = getattr(patch, func)
                original = getattr(cls, func, None)
                if original:
                    setattr(cls, func, _wrap_fun(wrapper, original))
                else:
                    setattr(cls, func, wrapper)
        return patch
    return _wrap_cls