[Python-Dev] Removing types module from stdlib
Guido van Rossum
Fri, 31 May 2002 12:03:54 -0400
> There were a couple of threads on comp.lang.py with headings like
> "isinstance considered harmful". The conclusion was that most cases
> should have been coded some other way. The legitimate uses included
> implementing multiple dispatch (supporting calls with type
> differentiated signatures) , factory functions, decorator pattern
> (which needs to know if the object was previously decorated), and
> the composite pattern (which needs to know if it is dealing with an
> atom or a composite).
Missing from the list is the important use case where it is known that
something you are going to do only works for a specific built-in type.
E.g. marshal.dump() requires a real file (and no, don't bother
"fixing" this -- marshal is sufficiently close to the implementation
that I don't want it to be fixed). There are also places where a
built-in int is required.
> Here are some of the ideas for conversion:
> if type(x) is int --> if x==int(x) # 3L would be passable
-1. This dies with a TypeError if x can't be converted to int.
> if type(x) == types.FileType --> if hasattr(x, 'read') # StringIO would
If that's what you want. But you should test for the method you're
actually going to call, often readline, or write. (Don't test for
multiple methods though -- that's too much).
> if type(x) is str: x = x.lower() -->
> x = x.lower()
> except AttributeError:
Hm, I hate to see try/except proliferated like this. Why is this
needed in the first place? Can't you write "x = x.lower()" without
> If the type check is meant to verify that an interface is supported,
> the try/except form maximized substitutability of objects which
> simulate the interface (like a UserDict or Shelve in place of a
In general I think explicit type checks are for wimps.
> I'm not sure this kind of conversion should be done everywhere but
> it could be an opportunity to remove unnecessary type dependencies.
I'd be careful. Knowing what's right requires deep understanding of
what the code is doing. If today it says type(x) is types.StringType,
I'm comfortable that isinstance(x, str) will do the right thing; not
about any of the alternatives.
I propose that if you find a place that looks like it is making too
strict a type assertion, report it here or in the SF bug tracker
before fixing it.
--Guido van Rossum (home page: http://www.python.org/~guido/)