How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)
+11
A:
Use isinstance(item, type)
-- for instance:
if isinstance(foo, int):
pass # handle this case
However, explicit type checking is not considered a good practice in the Python world -- it means that much of the power of duck typing is lost: Something which walks and quacks like a duck should be allowed to be a duck, even if it isn't! :)
Charles Duffy
2009-02-07 22:42:24
It's called isinstance() in Python
David Zaslavsky
2009-02-07 22:43:05
Yup, caught that myself -- was fixing it as you replied.
Charles Duffy
2009-02-07 22:43:43
Using type() to check equality means that instances of a subclass aren't recognized, so it's not usually the Right Thing.
Charles Duffy
2009-02-07 22:47:31
Well, usually yes. Very occasionally you do still want type()... difficult to call without any context though. I don't know of any API that uses a variant that could be an int or SQLite cursor!
bobince
2009-02-07 23:19:34
Yes, right, and I think that also points back to what Charles said, that using either "type" or "isinstance" is usually not considered good practice. There probably are valid uses, but you may want to think once more about what you are trying to do before actually using any of them.
Johan
2009-02-08 10:41:45