How to define the size of a tuple or a list in the type hints

Viewed 2847

Is there a way to define the size of a tuple or list in the type hints of arguments?

At the moment I am using something like this:

    from typing import List, Optional, Tuple

    def function_name(self, list1: List[Class1]):
        if len(list1) != 4:
            raise SomeError()
        pass
        # some code here

I am searching for a leaner way to do this.

3 Answers

For lists it make no sense because they are dynamic, for tuples on the other hand the number of types inside the definition is the number of elements it holds:

from typing import Tuple

example_1: Tuple[int, int] = (1, 2)  # This is valid
example_2: Tuple[int, int] = (1, 2, 3)  # This is invalid
example_3: Tuple[int, ...] = (1, 2, 3, 4)  # This is valid, the ellipses means any number if ints
example_4: Tuple[int, ...] = (1, 'string')  # This is invalid

# So in your case if you need 4 you can do something like this
My4Tuple = Tuple[Class1, Class1, Class1, Class1]
def my_function(self, arg1: My4Tuple):
    pass

Always remember that this is not enforced at runtime

One way is to change the signature to accept 4 parameters:

def function_name(self, c1, c2, c3, c4): # Use better parameter names
    pass

Then you can call this with a list by using the splat operator:

l = [...]
x.function_name(*l)

Why don't you just have it take in 4 arguments? Then, you can do something like this:

def function_name(self, a: Class1, b: Class1, c:Class1, d:Class1):
    ...

data = (Class1(...), Class1(...), Class1(...), Class1(...))
obj.function_name(*data)
Related