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?

3
  • Are you asking for the correct way of doing function annotations? Commented Jun 14, 2022 at 11:17
  • 1
    I can't confirm it, but it's incorrect to return NoReturn from the annotation. NoReturn should be used to annotate the return type of the function which end with raise Exception. Commented Jun 14, 2022 at 11:18
  • @MechanicPig Thanks fr pointing that out! I Will adjust the question. Commented Jun 14, 2022 at 11:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.