Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct way to use typing in Python 3.8+ for unpacked arguments

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading