How can I type-check variables in Python?

后端 未结 9 1585
南旧
南旧 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:25
    isinstance(n, int)
    

    If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this):

    type(n) is int
    

    this:

    return int(n) == n
    

    isn't such a good idea, as cross-type comparisons can be true - notably int(3.0)==3.0

    0 讨论(0)
  • 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 ...

    0 讨论(0)
  • 2020-12-15 04:34

    Don't type check. The whole point of duck typing is that you shouldn't have to. For instance, what if someone did something like this:

    class MyInt(int):
        # ... extra stuff ...
    
    0 讨论(0)
提交回复
热议问题