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

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

if var.isPrimitive():


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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.

Solution 4:[4]

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

Solution 5:[5]

For Python 2.7, you may want to take a look at types module, that lists all python built-in types.

https://docs.python.org/2.7/library/types.html

It seems that Python 3 does not provide the same 'base' type values as 2.7 did.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Community
Solution 4 9000
Solution 5