[Python-Dev] reflections on basestring -- and other abstractbasetypes

Phillip J. Eby pje at telecommunity.com
Mon Nov 3 11:44:12 EST 2003


At 05:02 PM 11/3/03 +0100, Alex Martelli wrote:

>Let me offer just a couple of use cases, one per kind.  For example,
>
>def __mul__(self, other):
>     if isinstance(other, self.KnownNumberTypes):
>         return self.__class__([ x*other for x in self.items ])
>     else:
>         # etc etc, various other multiplication cases
>
>right now, that (class, actually) attribute KnownNumberTypes starts out
>"knowing" about int, long, float, gmpy.mpz, etc, and may require user
>customization (e.g by subclassing) if any other "kind of (scalar) number"
>needs to be supported; besides, the isinstance check must walk linearly
>down the tuple of known number types each time.  (I originally had
>quite a different test structure:
>     try: other + 0
>     except TypeError:  # other is not a number
>         # various other multiplication cases
>     else:
>         # other is a number, so...
>         return self.__class__([ x*other for x in self.items ])
>but the performance for typical benchmarks improved with the isinstance
>test, so, reluctantly, that's what I changed to).  If an abstract basetype
>'basenumber' caught many useful cases, I'd put it right at the start of
>the KnownNumberTypes tuple, omit all subclasses thereof from it, get
>better performance, AND be able to document very simply what the user
>must do to ensure his own custom type is known to me as "a number".

This is the sort of thing that just begs for open generic functions with 
multiple dispatch, though.  Even object adaptation doesn't easily 
generalize to operations better expressed as f(x,y) than x.f(y).




More information about the Python-Dev mailing list