How to compare type of an object in Python?


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.

9/11/2015 12:09:50 PM

Accepted Answer


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

You may also want to read this:

9/1/2011 3:25:10 AM

isinstance works:

if isinstance(obj, MyClass): do_foo(obj)

but, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.

EDIT: For the None type, you can simply do:

if obj is None: obj = MyClass()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow