How to compare type of an object in Python?

Joan Venge picture Joan Venge · Apr 2, 2009 · Viewed 239.4k times · Source

Basically I want to do this:

obj = 'str'
type ( obj ) == string

I tried:

type ( obj ) == type ( string )

and it didn't work.

Also, what about the other types? For example, I couldn't replicate NoneType.

Answer

anthony picture anthony · Apr 2, 2009
isinstance()

In your case, isinstance("this is a string", str) will return True.

You may also want to read this: http://www.canonical.org/~kragen/isinstance/