Using isinstance
limits the objects which you can pass to your function. For example:
def add(a,b):
if isinstance(a,int) and isinstance(b,int):
return a + b
else:
raise ValueError
Now you might try to call it:
add(1.0,2)
expecting to get 3
but instead you get an error because 1.0
isn't an integer. Clearly, using isinstance
here prevented our function from being as useful as it could be. Ultimately, if our objects taste like a duck when we roast them, we don't care what type they were to begin with just as long as they work.
However, there are situations where the opposite is true:
def read(f):
if isinstance(f,basestring):
with open(f) as fin
return fin.read()
else:
return f.read()
The point is, you need to decide the API that you want your function to have. Cases where your function should behave differently based on the type exist, but are rare (checking for strings to open files is one of the more common uses that I know of).