[Python] Can a decorator be used to define type hints for the decorated function?

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    Given a decorator that injects an argument into the decorated function like the following dumb example:

    from typing import Callable
    import time

    def pass_timestamp(fn: Callable[[float], None]) -> Callable[[], None]:
    def wrapper():
    fn(time.time())

    return wrapper


    Is it possible that the type of the injected value is "pushed" into the decorated function so that I don't need to annotate the parameter? For example:

    @pass_timestamp
    def some_func(ts):
    reveal_type(ts) # <-- I'd like to get "float".


    I'm afraid the answer is no, but I'd be happy to be wrong.

    Continue reading...

Compartilhe esta Página