Nope, in fact it's overwhelmingly common not to test for type values, as in your second approach. The idea is that a client of your code (i.e. some other programmer who uses your class) should be able to pass any kind of object that has all the appropriate methods or properties. If it doesn't happen to be an instance of some particular class, that's fine; your code never needs to know the difference. This is called duck typing, because of the adage "If it quacks like a duck and flies like a duck, it might as well be a duck" (well, that's not the actual adage but I got the gist of it I think)
One place you'll see this a lot is in the standard library, with any functions that handle file input or output. Instead of requiring an actual file
object, they'll take anything that implements the read()
or readline()
method (depending on the function), or write()
for writing. In fact you'll often see this in the documentation, e.g. with tokenize.generate_tokens
, which I just happened to be looking at earlier today:
The generate_tokens()
generator requires one argument, readline, which must be a callable object which provides the same interface as the readline()
method of built-in file objects (see section File Objects). Each call to the function should return one line of input as a string.
This allows you to use a StringIO
object (like an in-memory file), or something wackier like a dialog box, in place of a real file.
In your own code, just access whatever properties of an object you need, and if it's the wrong kind of object, one of the properties you need won't be there and it'll throw an exception.