How can I type-check variables in Python?

后端 未结 9 1616
南旧
南旧 2020-12-15 03:59

I have a Python function that takes a numeric argument that must be an integer in order for it behave correctly. What is the preferred way of verifying this

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 04:09

    I would be tempted to to something like:

    def check_and_convert(x):
        x = int(x)
        assert 0 <= x <= 255, "must be between 0 and 255 (inclusive)"
        return x
    
    class IPv4(object):
        """IPv4 CIDR prefixes is A.B.C.D/E where A-D are 
           integers in the range 0-255, and E is an int 
           in the range 0-32."""
    
        def __init__(self, a, b, c, d, e=0):
            self.a = check_and_convert(a)
            self.b = check_and_convert(a)
            self.c = check_and_convert(a)
            self.d = check_and_convert(a)
            assert 0 <= x <= 32, "must be between 0 and 32 (inclusive)"
            self.e = int(e)
    

    That way when you are using it anything can be passed in yet you only store a valid integer.

提交回复
热议问题