isinstance() considered harmful

Kragen Sitaker kragen at pobox.com
Thu Jan 24 02:03:24 EST 2002


"Jason Orendorff" <jason at jorendorff.com> writes:
> Kragen Sitaker wrote:
> > isinstance() considered harmful
> 
> I've been thinking about this, and I'd be a lot happier
> with it if:
> 
>  (a) code using "try: ... except AttributeError:" were even
>      remotely as clear as code using isinstance();

hasattr isn't too much worse, especially if the attribute is something
like fileno or keys.  But it is less clear.

Generally, though, even the try: except AttributeError: code is a
mistake.  There are exceptions.

>  (b) it left room for writing much faster Python code in a
>      future version, the way explicit interfaces do; and

Can you elaborate?  Are you talking about vtables?

>  (c) there were a way to make sure that "x.seek" is really
>      a file.seek() method, and not something else.

Avoiding name collisions, you mean?  I think that's a very reasonable
thing to want.

> I like the potential performance upside of static typing in
> Python.

Well, there are three proven ways to get fast compiled code by having
the compiler know what types it's compiling code for:
- you can have static types, either declared like C or inferred like ML
- you can do dynamic code optimization and specialization like Java and Self
- you can have optional type annotations like Common Lisp

There's also a fourth way, Stalin-style type inference, which doesn't
work as well as I'd like in my experience --- it's hard to tell why
the compiler is too stupid to understand that a particular piece of
code could be compiled much more efficiently and what you should
change in the source code to fix it.

> I wish I could say "if supports(object, wfile.write): ..."
> instead of "if hasattr(object, 'write'): ..."
> or the equivalent try/except/else incantation.

That would be really nice.

> Note also that the distutils policy of requiring extensions
> to subclass Distribution has an important purpose: to ensure
> that future versions of distutils can add methods to
> Distribution, and Command can then safely use those methods.

I understand that this is desirable, but I think there are usually
(always?) better ways to handle this.




More information about the Python-list mailing list