Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

if var.isPrimitive(): 
like image 699
telekinki Avatar asked Jun 17 '11 20:06

telekinki


People also ask

How do you know if a type is primitive?

The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.

Is primitive type Java?

Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.

Which is a primitive type variable declaration?

The 8 Primitive Variable Typesbyte , short , int , long , float , double , char , boolean .


1 Answers

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 
like image 172
pillmuncher Avatar answered Oct 01 '22 20:10

pillmuncher