50

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

if var.isPrimitive():
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
telekinki
  • 535
  • 1
  • 4
  • 4
  • 11
    What is a "primitive" type in Python? :) (Some types act *a little funny* in CPython 2.x, because of how they are [natively] implemented, yet there is no notion of a "primitive" type.) –  Jun 17 '11 at 20:55
  • 2
    What do you mean by "is primitive"? I don't think Python has primitives the way Java does. – Chris Lutz Jun 17 '11 at 20:56
  • 1
    well, I guess if it is a bool or a str, or a numeric variable... – telekinki Jun 17 '11 at 20:57
  • 1
    A String isn't primitive in Java ;-) Anyway, consider updating the original post with particular requirements and/or a use-case. It will likely lead to (better) replies. –  Jun 17 '11 at 21:01
  • 2
    well... why do you consider a `str` a primitive type? In Java it's an Object. In C, it's an array of chars (which are primitive types). – iliaden Jun 17 '11 at 21:01
  • possible duplicate of [Determine if Python variable is an instance of a built-in type](http://stackoverflow.com/questions/1322068/determine-if-python-variable-is-an-instance-of-a-built-in-type) – slhck Apr 16 '15 at 14:09
  • 1
    @slhck: **Definitely *not* a duplicate of [Determine if Python variable is an instance of a built-in type](http://stackoverflow.com/questions/1322068/determine-if-python-variable-is-an-instance-of-a-built-in-type).** See [dcmorse](https://stackoverflow.com/users/4106215/dcmorse)'s [response that erroneously conflates primitive with builtin types](https://stackoverflow.com/a/46024372/2809027) to grok why. (Hint: _if all builtin types are primitives, then all standard exception types are primitives, at which point any semblance of sanity has vacated the premises._) – Cecil Curry Feb 28 '19 at 05:29

8 Answers8

44

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
pillmuncher
  • 10,094
  • 2
  • 35
  • 33
35

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
VigneshChennai
  • 570
  • 4
  • 9
  • So by this rule, *type* and *function* are not primitive? I'm sure there is a way for OP to rephrase his/her code so that it doesn't require an arbitrary distinction between 'primitive' and 'aggregate' types. – jforberg Jan 18 '14 at 21:08
  • 2
    I think there is some confusion with what is a primitive and what is a standard class or a built-in function. Primitives are primitive, they are simple and represent a single piece of data like. __dict__ is special attribute that is used to store an object’s (writable) attributes. If the object doesn't have attributes, its a primitive. If you pass the above function int for example or str: isPrimitive(int) it will say False because it does have a __dict__ attribute. So classes and functions are not considered as primitive even though an int or str or float , etc.. piece of data is a primitive – radtek Jul 10 '14 at 20:07
  • 1
    I believe this won't work with objects that use `__slots__`, as @Mark asked. Can anyone confirm? – Asker Oct 22 '18 at 20:40
  • 2
    **This is objectively horrible.** The `isPrimitive()` function name is a blatant misnomer here guaranteed to return false positives. Never do this in production code, people. As defined, what this function *actually* tests is whether or not the passed object is slotted (i.e., has defined the `__slots__` class dunder variable), which in turn has little to do with whether or not the passed object satisfies your purely subjective definition of "primitive." – Cecil Curry Feb 28 '19 at 04:13
33

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.

Community
  • 1
  • 1
jforberg
  • 6,537
  • 3
  • 29
  • 47
  • 1
    OK, so if everything is an object, why can I do "1".__eq__("2") => False, but not 1.__eq__(2) => SyntaxError: invalid syntax ? Surprising... – Matthew Cornell Sep 04 '12 at 19:35
  • 8
    This is because a number can include a point (e.g. 1.23 is just a number, as is 0.e2). This confuses the parser. If you wrap the number in parentheses, it will work. (1).__eq__(2) => False. However, you seldom need to do this in Python. – jforberg Sep 08 '12 at 13:22
  • how about something that registers as a simple serializable value, instead of a structure that is meant to be and is interpreted by the vast majority of built in types as a primitive value. – John Sohn Sep 18 '21 at 15:44
  • printing a string doesn't result in a reference type output or 'value=kkjlkjjljkj length=x' – John Sohn Sep 18 '21 at 15:44
7

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
9000
  • 39,899
  • 9
  • 66
  • 104
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.

rotoglup
  • 5,223
  • 25
  • 37
2

isinstance(obj, (str, numbers.Number) should be close enough:

python type hiearchy

Lajos
  • 2,549
  • 6
  • 31
  • 38
1

Hmm, I had this problem in the past. I think the best solution is to check if object is Hashable.

from collections.abc import Hashable
isinstance(element, Hashable)
-5

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'>
lprsd
  • 84,407
  • 47
  • 135
  • 168
  • No, you are missing the point here. The topic starter wants to find out if a variable `foo` is a "primitive" (non-complex) type, like `float`, `int`, `str`, `bool` and alike. So checking `type(foo) in {int, str, bool, float, ...)` would be more the proper answer. – Roland Jun 02 '23 at 11:38