Home > other >  Describing complex return type of the method
Describing complex return type of the method

Time:08-04

I'm trying to define return type of the method in Python (3.8.9). Ideally, return type should be list of tuple of int. My first natural solution, as I came from strongly typed world, was def .... -> list(tuple(int,int)).

Unfortunately this doesn't work and bring runtime exception

tuple expected at most 1 argument, got 2

As per documentation section Type Alias defining type like list[int] or tuple[int] should work but in my code I'm getting same error even if C/P code from documentation.

Is type hint feature is version specific? What am I missing?

CodePudding user response:

You are using round brackets, while the documentation specifies square brackets.

Try this, for example:

def fn() -> list[tuple[int, int]]:
    return [(1, 2), (3, 4)]

Or, if you are using Python versions older than 3.9, try this:

from typing import List, Tuple


def fn() -> List[Tuple[int, int]]:
    return [(1, 2), (3, 4)]
  • Related