Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether the type of a variable is a specific type in Python

Tags:

python

I want to check whether the type of a variable is a specific kind in Python. For example- I want to check if var x is an int or not.

>>x=10
>>type(x)
<type 'int'>

But how can I compare their types. I tried this, but it doesn't seem to work.

if type(10)== "<type 'int'>":
    print 'yes'

How can I do this ?

like image 440
OneMoreError Avatar asked Oct 17 '25 04:10

OneMoreError


1 Answers

Use the isinstance() function to test for a specific type:

isinstance(x, int)

isinstance() takes either a single type, or a tuple of types to test against:

isinstance(x, (float, complex, int))

would test for a series of different numeric types for example.

like image 79
Martijn Pieters Avatar answered Oct 18 '25 20:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!