简体   繁体   中英

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

  • Zac

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM