tags:

views:

219

answers:

2

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
It's called isinstance() in Python
David Zaslavsky
Yup, caught that myself -- was fixing it as you replied.
Charles Duffy
A: 

Use the built-in "type" function, e.g. type(10) -> .

Johan
Using type() to check equality means that instances of a subclass aren't recognized, so it's not usually the Right Thing.
Charles Duffy
Yeah, sorry, you are right, isinstance is the better choice.
Johan
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
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