How can I type-check variables in Python?

后端 未结 9 1602
南旧
南旧 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:31

    how about:

    def ip(string):
        subs = string.split('.')
        if len(subs) != 4:
            raise ValueError("incorrect input")
        out = tuple(int(v) for v in subs if 0 <= int(v) <= 255)
        if len(out) != 4:
            raise ValueError("incorrect input")
        return out
    

    ofcourse there is the standard isinstance(3, int) function ...

提交回复
热议问题