from typing import Any


def monkeypatch(obj: Any, attr: str, new: Any) -> Any:
    """Temporarily replace a method with a new funtion

    The previously set method is passed as the first argument to the new function
    """

    def patched(*args: Any, **kwargs: Any) -> Any:
        return new(old, *args, **kwargs)

    old = getattr(obj, attr)

    try:
        setattr(obj, attr, patched)
        yield
    finally:
        setattr(obj, attr, old)