Mypy: How to properly type a decorator which injects a parameter

Created on 27 Feb 2018  路  1Comment  路  Source: python/mypy

How would I properly type this code?

from functools import wraps
from typing import *

Params = TypeVar('Params')
Return = TypeVar('Return')


def decorator(f: Callable[Params, Return]) -> Callable[[str, *Params], Return]:
    @wraps(f)
    def wrapper(*args: Params):
        return f('injected', *args)
    return wrapper


@decorator
def func(injected: str, prefix: str, num: int) -> str:
    return prefix + (injected * num)


assert func('hello', 2) == 'helloinjectedinjected'

The Callable[Params, Return] and Callable[[str, *Params], Return] are the problem here. Is there a way to type this?

Most helpful comment

This is not currently possible. There's a proposal for an extension to PEP 484 that would allow such types to be expressed though: https://github.com/python/typing/issues/193

>All comments

This is not currently possible. There's a proposal for an extension to PEP 484 that would allow such types to be expressed though: https://github.com/python/typing/issues/193

Was this page helpful?
0 / 5 - 0 ratings