0

Please consider the following example in Python 3.8+. Assume a function which gets any number of arguments, all of the same type. For example

def fun(*foos):
    for foo in foos:
        foo.do_something()

I would like to add typing for the foos argument, for this reason assume that all arguments are of the same type foo_type. What is the correct way for typing?

For me the following would be the obvious typing:

from typing import Tuple

def fun(*foos: Tuple[foo_type]) -> None:
    for foo in foos:
        foo.do_something()

My IDE (CLion) suggest:


def fun(*foos: foo_type) -> None:
    for foo in foos:
        foo.do_something()

Which way of typing for the foos argument is correct, and why?

1 Answers1

1

I'm not sure what prompted the question, the answer is (as your IDE already told you):

def fun(*foos: foo_type) -> NoReturn:
    for foo in foos:
        foo.do_something()

If you instead had something like this:

def fun(foos: Tuple[foo_type]) -> NoReturn:
    for foo in foos:
        foo.do_something()

That would work as well, but of course that would require calling the function with an actual tuple of foo_type elements.

In fun(*foos: foo_type), the unpacked foos is defined to be of foo_type, which is what you want. If you do this instead:

def fun(*foos: Tuple[foo_type]) -> NoReturn:
    for foo in foos:
        foo.do_something()

Then you'll get errors, since a tuple doesn't have a do_something() (unless you give it one), but you'll still get type hints.

Grismar
  • 27,561
  • 4
  • 31
  • 54