pythonpython-typing

Enforce type hinting in Python class


I need to enforce the type of a class variable, but more importantly, I need to enforce a list with its types. So if I have some code which looks like this:

class foo:
    def __init__(self, value: list[int]):
        self.value = value

How can I make sure that value is a list of integers?

I'm using Python version 3.9.4.


Solution

  • One way is to check the instances type directly and raise error if they're not in the types you want.

    class foo:
        def __init__(self, value):
            if not isinstance(value, list) or not all(isinstance(x, int) for x in value):
                raise TypeError("value should be a list of integers")
                
            self.value = value