Zachary
Zachary

Reputation: 570

Python class enforce type hinting

So 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

Btw I'm using python version 3.9.4

So essentially my question is, how can I make sure that value is a list of integers.

Thanks in advance

Upvotes: 1

Views: 1297

Answers (2)

aminrd
aminrd

Reputation: 5070

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

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 118001

In addition to type checking (which is only enforced by linters) you could assert

class foo:
    def __init__(self, value: list[int]):
        assert isinstance(value, list) and all(isinstance(i, int) for i in value)
        self.value = value

>>> foo([1,2,3])  # good
<__main__.foo object at 0x000001EB492A5940>

>>> foo('abc')  # bad
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    foo('abc')
  File "<pyshell#1>", line 3, in __init__
    assert isinstance(value, list) and all(isinstance(i, int) for i in value)
AssertionError

>>> foo([1.0, 2.0, 3.0])  # bad
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    foo([1.0, 2.0, 3.0])
  File "<pyshell#1>", line 3, in __init__
    assert isinstance(value, list) and all(isinstance(i, int) for i in value)
AssertionError

In addition to a simple assertion, you could also raise and perhaps implement a custom exception for callers to handle these.

Upvotes: 1

Related Questions