def monkeypatch_method(cls):
    """ Add the decorated method to the given class; replace as needed.

        If the named method already exists on the given class, it will
        be replaced, and a reference to the old method appended to a list
        at cls._old_<name>. If the "_old_<name>" attribute already exists
        and is not a list, KeyError is raised.

        Example usage::

            from <somewhere> import <someclass>

            @monkeypatch_method(<someclass>)
            def <newmethod>(self, args):
                return <whatever>

        This adds <newmethod> to <someclass>

        Origin: http://goo.gl/C1v0z
    """

    def decorator(func):
        fname = func.__name__

        old_func = getattr(cls, fname, None)
        if old_func is not None:
            # Add the old func to a list of old funcs.
            old_ref = "_old_%s" % fname
            old_funcs = getattr(cls, old_ref, None)
            if old_funcs is None:
                setattr(cls, old_ref, [])
            elif not isinstance(old_funcs, list):
                raise KeyError("%s.%s already exists." %
                    (cls.__name__, old_ref))
            getattr(cls, old_ref).append(old_func)

        setattr(cls, fname, func)
        return func

    return decorator