How to check if a variable's type is primitive?

前端 未结 7 1183
难免孤独
难免孤独 2020-12-05 12:57

I don\'t know how to check if a variable is primitive. In Java it\'s like this:

if var.isPrimitive():
7条回答
  •  爱一瞬间的悲伤
    2020-12-05 13:43

    Since there are no primitive types in Python, you yourself must define what you consider primitive:

    primitive = (int, str, bool, ...)
    
    def is_primitive(thing):
        return isinstance(thing, primitive)
    

    But then, do you consider this primitive, too:

    class MyStr(str):
        ...
    

    ?

    If not, you could do this:

    def is_primitive(thing):
        return type(thing) in primitive
    

提交回复
热议问题