What's the canonical way to check for type in Python?

后端 未结 13 1062
南旧
南旧 2020-11-21 07:34

What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?

Let\'s say I have an objec

13条回答
  •  误落风尘
    2020-11-21 08:05

    For more complex type validations I like typeguard's approach of validating based on python type hint annotations:

    from typeguard import check_type
    from typing import List
    
    try:
        check_type('mylist', [1, 2], List[int])
    except TypeError as e:
        print(e)
    

    You can perform very complex validations in very clean and readable fashion.

    check_type('foo', [1, 3.14], List[Union[int, float]])
    # vs
    isinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) 
    

提交回复
热议问题