Python type hint for returning one of two different tuples

  Kiến thức lập trình

I’m working with legacy code which returns a single tuple, but with changes will return the original tuple, or another tuple with an additional value. Basically like this:

1  #!/usr/bin/python
2  from typing import Union
4  def func(x):
5      # type: (bool) -> Union[tuple[str, int], tuple[str, str, int]]
6      if x:
7          return "one", "two", 0
8      return "one", 0
10  one, two = func(False)
11  print(f"{one} {two}")
12  one, two, three = func(True)
13  print(f"{one} {two} {three}")

The code works as expected:

$ ./
one 0
one two 0

But when I run mypy on it, I get:

$ mypy error: Too many values to unpack (2 expected, 3 provided)  [misc] error: Need more than 2 values to unpack (3 expected)  [misc]
Found 2 errors in 1 file (checked 1 source file)

Am I missing something or is this an issue with mypy?