As we all know, when we are using a dynamic language such as Python, we don't have to worry about Types. Because dynamic typing let us work without that concern. Even so, we can know the types of variables using the function type() (in Python). So my question is: What good do type checking in a dynamic language?
There are a few cases where type checking is something you want to do. Say, for example, you want to work with iterators, but not strings - this is a pretty common case. The best way to make that check is to type check if the item is a string:
if isinstance(someobj, str): # basestring in 2.x
...
We use isinstance() as it allows for subclasses as well as instances of the class itself. Checking directly using type() is pretty much universally a terrible idea, but type() does have other uses - sometimes you want to access the class of an instance for reasons other than type checking.
It's also worth noting that Python allows the definition of abstract base classes with a subclass hook - this allows isinstance() to do a kind of duck type check, where the class is checked for the relevant methods required. For example, if you want to check something is a Sequence, doing isinstance(obj, collections.Sequence) is not bad, as it's not actually type-checking in a traditional sense, it checks if the object has the functions necesary for the sequence interface (as defined in the docs).
In general, however, type checking should be avoided. In most cases, it's possible to simply try and do what you want, and then catch exceptions if the object can't do what it needs to. Python generally follows the rule of ask for forgiveness, not permission, so try it and gracefully handle errors, rather than checking beforehand.
In short: in a dynamic language, we rely on duck-typing. If an object can quack, we can assume it's a duck. 99% of the time, and object that can quack can be treated as a duck, so we are fine. However, in rare cases, another animal that can quack should not be treated as a duck. The only way we can distinguish between them is to type check, and that is OK. Type checking should not be used to check if our animal can quack, however, as we can just try and see (or, if we can't make it quack right now, but still need to operate dependent on it, check directly for the ability to quack, rather than checking for a type we know can quack).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With