5

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

pstatix
  • 3,611
  • 4
  • 18
  • 40
  • 2
    Don't Repeat Yourself should be called Don't Be Redundant. Just because you are repeating something doesn't mean you don't have to (or shouldn't) repeat it. – chepner Jan 10 '20 at 19:45
  • @chepner Technically, there's no repeats here. `a != b != c` – r.ook Jan 10 '20 at 20:27

2 Answers2

6

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.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

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
r.ook
  • 13,466
  • 2
  • 22
  • 39