[Python] In Python, how to use a decorator to mark a keyword-only mandatory argument as...

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    So, I have a bunch of functions that all have a certain keyword argument, let's call it kw, which is mandatory and has a specific type T. However, I want to be able to call the functions without necessarily providing that keyword argument, and if it's not present I want it to be generated, probably through a decorator. Furthermore, I want my IDE to show its signature as if kw were optional.

    In other words, I have functions that have a signature kind of like this:

    def f(*args, kw: T, **kwargs): ...


    I want their signature to look something like this to my IDE and type checker:

    [​IMG]

    (Since each function might have other positional and/or keyword arguments.)

    It seems to me like I should be able to have some decorator sort of like this:

    def decorator(func):
    sig = inspect.signature(func)
    hints = get_type_hints(func)
    orig_ann = hints.get("kw")
    new_ann = Optional[orig_ann]

    new_params = []
    for param in sig.parameters.values():
    if param.name == "kw":
    new_params.append(
    param.replace(
    annotation=new_ann,
    default=None,
    )
    )
    else:
    new_params.append(param)

    new_sig = sig.replace(parameters=new_params)

    @wraps(func)
    def wrapper(*args, **kwargs):
    if kwargs.get("kw") is None:
    kwargs["kw"] = some_function_or_something()
    return func(*args, **kwargs)

    "do something to update the signature"
    return wrapper


    But I cannot for the life of me figure out what I would need to do to get that to happen. Is it possible? How would I do it if so?

    Continue reading...

Compartilhe esta Página