Who's minister of propaganda this week?

Neelakantan Krishnaswami neelk at alum.mit.edu
Fri Mar 16 23:01:06 EST 2001


On Fri, 16 Mar 2001 15:33:08 +0100, Alex Martelli <aleaxit at yahoo.com> wrote:
>"Neelakantan Krishnaswami" <neelk at alum.mit.edu> wrote in message
>news:slrn9b2u0r.j74.neelk at alum.mit.edu...
>    [snip]
>> > Keying a dict on class has the unfortunate side-effect of
>> > not allowing polymorphism by inheritance -- objects of classes
>> > _derived from_ the one used as the key will not match.
>> >
>> > You can preserve this basic idea by using as key, instead of the
>> > class, some ad-hoc attribute which will be inherited (if it IS
>    [snip]
>> I actually have a function that walks the class tree checking it
>> against the dictionary, which solves this problem.  You don't need to
>> add a special attribute in Python since __class__ gives you what you
>> need for free.
>
> ...except it doesn't, because it's _not_ inherited -- you have
> to 'manually' walk the directed acyclic graph (tree? what tree?
> we have _multiple_ inheritance:-) or iterate through the dictionary's
> keys (assumed to be types) using isinstance for each on your
> object.

Okay, I don't understand what you're saying at all.

If I call __class__ on an object, I get its class. Now, I can ask
each class what its superclasses are using the __bases__ attribute on
each class. This is okay to leave as a function, because Python
promises to walk the class heterarchy (happy? :) in a depth-first
left-to-right order.

So I have a dictionary like this

>>> d
{<class Bar at 80ea570>:   2,
 <class Glarp at 80e9bd8>: 3,
 <class Foo at 80dcff8>:   1}

and when I call lookup(d, Baz()) where Baz is a direct subclass of
Foo, it will return 1. (C types are easy to handle, because they don't
admit any subtyping.)

Am I off-base here?

>> I only added it to my toolkit recently, though, sine I tend to use
>> classes like algebraic data types in ML or Haskell -- as tagged
>> variants rather than designed for user-extension. I find
>> subclassing friendly designs are a lot harder to design in a way
>> that doesn't reveal too much internal structure.
>
> Inheritance (of implementation) is strong coupling, yes.  But,
> it IS a very handy implementation technique [...]

No disagreement here. I'm just hesitant to use it much because I don't
want to accidentally break some invariant I accidentally left out of
my unit tests 6 months ago. :)

> Here's a sketch of a general-by-type dispatcher module to ensure one
> can dispatch on either type OR class (and in the latter case gets
> inheritance by default, unless it's explicitly overridden):

This looks a lot like the one I have, except that I pass all
information in arguments, and you've factored into smaller
functions. (Good for you!)


Neel




More information about the Python-list mailing list