Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 740
pstatix Avatar asked Mar 03 '23 22:03

pstatix


2 Answers

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.

like image 81
Carcigenicate Avatar answered Mar 20 '23 06:03

Carcigenicate


I think @Carcigenicate covered the topic pretty well, but since your concern is mostly notational and just want to make it look neat, you might consider using hanging indentation instead:

def foobar(a: int,
           b: int,
           c: int,
           d: str):
    pass
like image 28
r.ook Avatar answered Mar 20 '23 06:03

r.ook