Search code examples
pythontype-hinting

Python - how to type hint calling a function that returns a tuple?


Today I was surprised when I found out the following generates an error in Python (I'm using Python 3.8)

from typing import Tuple, List, Dict

def main():
    
    my_list: List, my_dict: Dict = my_function()   # this is the line I'm asking about

    print(my_list)
    print(my_dict)

# end function

def my_function() -> Tuple[List, Dict]:
    my_list = [1, 2, 3]
    my_dict = { 'one': 1, 'two': 2}
    return my_list, my_dict
# end function

if __name__ == '__main__':
    main()

result:

$ python3 data/scratchpad2.py 
  File "data/scratchpad2.py", line 7
    my_list: List, my_dict: Dict = my_function()
                 ^
SyntaxError: invalid syntax

If I take out the type hints where the function call is made everything works as expected. Am I just not entering the syntax quite right, or is this really not allowed? If this is not allowed, how can type hints be used when receiving a tuple from a function?


Solution

  • According to PEP-0526, you should annotate the types first, then do the unpacking

    a: int
    b: int
    a, b = t
    

    https://stackoverflow.com/a/52083314