What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let\'s say I have an objec
I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.
I would just call the required methods on your object and catch an AttributeError
. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.
I've used this a lot when getting data off the web with urllib2.urlopen()
which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read()
method as a real file.
But I'm sure there is a time and place for using isinstance()
, otherwise it probably wouldn't be there :)