Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 494
NameVergessen Avatar asked Nov 02 '25 14:11

NameVergessen


1 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

like image 189
Dalvenjia Avatar answered Nov 04 '25 05:11

Dalvenjia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!