Search code examples
pythonpython-typing

Type hinting for multiple parameters of same type?


Is there another way to type hint parameters of the same type other than:

def foobar(a: int, b: int, c: int, d: str): ...

Maybe something like:

def foobar([a, b, c]: int, d: str): ...

Obviously notional, but something to reduce repeating type hints


Solution

  • The only ways that I know involve "packaging" the parameters in some way.

    Due to how var-args work, you could shift your order a bit and take the arguments as var-args:

    def foobar(d: str, *args: int): …
    

    args now holds a, b, and c (along with whatever else is passed).

    Along the same lines, you could pass in a list:

    from typing import List
    
    def foobar(args: List[int], d: str): …
    

    Which is essentially the same as above.

    Of course though, these both come with the severe drawback that you no longer have the ability to static-check arity; which is arguably even worse of a problem than not being able to static-check type.

    You could mildly get around this by using a tuple to ensure length:

    from typing import Tuple
    
    def foobar(args: Tuple[int, int, int], d: str): …
    

    But of course, this has just as much repetition as your original code (and requires packing the arguments into a tuple), so there's really no gain.

    I do not know of any "safe" way to do literally what you want.