Is isinstance always "considered harmful"?
Terry Reedy
tjreedy at udel.edu
Sun May 15 14:31:21 EDT 2005
"Jordan Rastrick" <jrastrick at student.usyd.edu.au> wrote in message
news:1116157672.683839.49700 at o13g2000cwo.googlegroups.com...
> I've read arguments, here and elsewhere, to the effect that in Python
> isinstance should be avoided like the plague, except in a few very
> specific and narrow circumstances.
Putting it like this is rather extreme.
> Roughly speaking, due in part to
> Python's dynamic nature its better to concern yourself only with the
> interface an object provides, and not whether it happens to inherit
> from a given base class.
To my mind, your example of using isinstance to select a better (such as
speedier) subalgorithm for a special case is not just fine, but good
programming. (Selecting a subalgorithm that works more robustly is also a
good reason for special casing.) It is an internal matter whose externally
visible effect is to improve performance.
Using isinstance to unnecessarily narrow the domain is quite different. It
has the externally visible effect of degrading performance (to a nullity)
for arguments that the user might reasonably want to work.
Terry J. Reedy
More information about the Python-list
mailing list