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
3
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
9
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:

$ ./tt.py
one 0
one two 0

But when I run mypy on it, I get:

$ mypy tt.py
tt.py:10: error: Too many values to unpack (2 expected, 3 provided)  [misc]
tt.py:11: 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?

LEAVE A COMMENT