예제 #1
0
def wrapped_partial(func: FunctionType,
                    suggested: Optional[dict] = None,
                    **fixed) -> Callable:
    """Wrap a function, updating its signature but keeping its docstring.

    Parameters
    ----------
    func : FunctionType
        The function to be wrapped
    suggested : dict
        Keyword arguments that should have new default values
        but still appear in the signature.
    fixed : kwargs
        Keyword arguments that should be fixed by the wrapped
        and removed from the signature.

    Examples
    --------
    >>> from inspect import signature
    >>> def func(a, b=1, c=1):
    ...     print(a, b, c)
    >>> newf = wrapped_partial(func, b=2)
    >>> signature(newf)
    <Signature (a, *, c=1)>
    >>> newf(1)
    1 2 1
    >>> newf = wrapped_partial(func, suggested=dict(c=2), b=2)
    >>> signature(newf)
    <Signature (a, *, c=2)>
    >>> newf(1)
    1 2 2
    """
    suggested = suggested or {}
    partial_func = partial(func, **suggested, **fixed)

    fully_wrapped = update_wrapper(partial_func,
                                   func,
                                   injected=list(fixed.keys()),
                                   hide_wrapped=True)

    # Store all injected params,
    injected = getattr(func, "_injected", {})
    injected.update(fixed)
    fully_wrapped._injected = injected
    return fully_wrapped
예제 #2
0
파일: utils.py 프로젝트: thomasremke/xclim
def wrapped_partial(func: FunctionType, suggested: dict = None, **fixed):
    """Wrap a function, updating its signature but keeping its docstring.

    Parameters
    ----------
    func : FunctionType
        The function to be wrapped
    suggested : dict
        Keyword arguments that should have new default values
        but still appear in the signature.
    fixed : dict
        Keyword arguments that should be fixed by the wrapped
        and removed from the signature.

    Examples
    --------

    >>> from inspect import signature
    >>> def func(a, b=1, c=1):
            print(a, b, c)
    >>> newf = wrapped_partial(func, b=2)
    >>> signature(newf)
    (a, *, c=1)
    >>> newf(1)
    1, 2, 1
    >>> newf = wrapped_partial(func, suggested=dict(c=2), b=2)
    >>> signature(newf)
    (a, *, c=2)
    >>> newf(1)
    1, 2, 2
    """
    suggested = suggested or {}
    partial_func = partial(func, **suggested, **fixed)

    fully_wrapped = update_wrapper(partial_func,
                                   func,
                                   injected=list(fixed.keys()),
                                   hide_wrapped=True)
    return fully_wrapped
예제 #3
0
def test_update_wrapper_partial(partial_kind):
    wrapper = partial_kind.partial(wrappable_varkw_func, b=1)

    fully_wrapped = update_wrapper(wrapper, wrappable_varkw_func)
    assert fully_wrapped(1) == (1, 1)