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

前端 未结 7 1145
难免孤独
难免孤独 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:27

    It's not easy to say definitely what to consider 'primitive' in Python. But you can make a list and check all you want:

    is_primitive = isinstance(myvar, (int, float, bool)) # extend the list to taste
    
    0 讨论(0)
  • 2020-12-05 13:38

    You may want to take a look at types module, that lists all python built-in types.

    http://docs.python.org/library/types.html

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-05 13:47

    In Python, everything is an object; even ints and bools. So if by 'primitive' you mean "not an object" (as I think the word is used in Java), then there are no such types in Python.

    If you want to know if a given value (remember, in Python variables do not have type, only values do) is an int, float, bool or whatever type you think of as 'primitive', then you can do:

     if type(myval) in (int, float, bool, str ...):
          # Sneaky stuff
    

    (Need I mention that types are also objects, with a type of their own?)

    If you also need to account for types that subclass the built-in types, check out the built-in isinstance() function.

    Python gurus try to write code that makes minimal assumptions about what types will be sent in. Allowing this is one of the strengths of the language: it often allows code to work in unexpected ways. So you may want to avoid writing code that makes an arbitrary distinction between types.

    0 讨论(0)
  • 2020-12-05 13:49

    As every one says, there is no primitive types in python. But I believe, this is what you want.

    def isPrimitive(obj):
        return not hasattr(obj, '__dict__')
    
    isPrimitive(1) => True
    isPrimitive("sample") => True
    isPrimitive(213.1311) => True
    isPrimitive({}) => True
    isPrimitive([]) => True
    isPrimitive(()) => True
    
    
    class P:
        pass
    
    isPrimitive(P) => False
    isPrimitive(P()) => False
    
    def func():
        pass
    
    isPrimitive(func) => False
    
    0 讨论(0)
  • 2020-12-05 13:50

    If it helps,

    In [1]: type(1)
    Out[1]: <type 'int'>
    
    In [2]: type('a')
    Out[2]: <type 'str'>
    
    In [3]: (type(5.4)
    Out[3]: <type 'float'>
    
    In [5]: type(object)
    Out[5]: <type 'type'>
    
    In [8]: type(int)
    Out[8]: <type 'type'>
    
    0 讨论(0)
提交回复
热议问题