'isa' keyword

talin at acm dot org viridia at gmail.com
Thu Sep 1 03:52:54 EDT 2005


Although I realize the perils of even suggesting polluting the Python
namespace with a new keyword, I often think that it would be useful to
consider defining an operator for testing whether or not an item is a
member of a category.

Currently, we have the 'in' operator, which tests for membership within
a container, and that works very well -- in particular, it allows such
membership tests to be expressed in very natural way. So for example,
whereas in C++ I always have to say:

    if (dependencies.find( name ) != dependencies.end())

in Python I can simply say:

    if name in dependencies:

...which is much more readable and intuitive. At the same time,
however, I recognize that there is a logical difference between
membership in a container, and membership in a category. For example,
although a bear is a member of the class of mammals, it doesn't make as
much to say "if bear in mammal". Similarly, you wouldn't want to use
the 'in' keyword as a replacement for isinstance(), i.e. "if name in
str".

I propose the word 'isa' because the term 'isa hierarchy' is commonly
used to indicate a tree of types. So the syntax would look like this:

    if bear isa mammal:
    if name isa str:

(I suppose it would look prettier to put a space between "is" and "a",
but there are many obvious reasons why you don't want "a" to be a
keyword!)

The "isa" operator would of course be overloadable, perhaps by an
accessor functions called __isa__, which works similarly to
__contains__. The potential uses for this are not limited to
isinstance() sugar, however. For example:

    if image isa gif:
    elif image isa jpeg:
    elif image isa png:

In this case, we're not testing for object identity (which tests if two
variables are referring to the same object), or even object equivalence
(which tests of two objects are of equal value), nor are we testing for
membership within a container -- instead we're testing for membership
with a type hierarchy, where 'type' can be defined to mean whatever the
programmer wants.

Of course, at this point, I am sure that someone will point out that I
should be using method overloading and inheritance rather than explicit
testing of types. However, try writing an efficient __cmp__ function
solely by method overloading -- or any other function that deals with
more two object argument, where the action to be taken depends on the
combination of types of both arguments. This can be solved with
multi-method dispatch, but such methods are complex, non-standard, and
have somewhat dubious performance characteristics. Its generally faster
and simpler to dispatch based on the type of one of the arguments, and
then test the types of the other arguments.




More information about the Python-list mailing list