Python check if isinstance any type in list?

后端 未结 4 1211
北荒
北荒 2021-02-02 05:05

How do I pythonicly do:

var = 7.0
var_is_good = isinstance(var, classinfo1) or isinstance(var, classinfo2) or isinstance(var, classinfo3) or ... or  isinstance(v         


        
4条回答
  •  余生分开走
    2021-02-02 05:38

    You were pretty close with the title of your question already. You could use any and a list:

    var = 7.0
    var_is_good = any([isinstance(var, classinfo1),
                       isinstance(var, classinfo2),
                       isinstance(var, classinfo3), ...
                       isinstance(var, classinfoN)])
    

    But looking in the docs of isinstance reveals:

    Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is not a class (type object), it may be a tuple of type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

    This means the better way to do it is

    var = 7.0
    var_is_good = isinstance(var, (classinfo1,
                                   classinfo2,
                                   classinfo3,
                                   ...,
                                   classinfoN))
    

提交回复
热议问题