Who's minister of propaganda this week?

Alex Martelli aleaxit at yahoo.com
Sat Mar 17 03:30:07 EST 2001


"Neelakantan Krishnaswami" <neelk at alum.mit.edu> wrote in message
news:slrn9b5sbv.lu3.neelk at alum.mit.edu...
    [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 far, so good.


> 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.)

That depends on how you have coded your lookup function,
of course; basically, it needs to duplicate the logic of Python's
bases-lookup (left-first, depth-first) unless you want to risk
some big surprise.

Consider, for example:

class Baz(Bar, Foo):
    pass

Now, Baz IS a direct subclass of Foo -- but I would expect the
lookup to yield 2, not 1, because Bar 'dominates' Foo in Baz's
ancestors-DAG -- and directness is less important than other
issues, e.g:

class Baz2(Baz,Foo):
    pass

this inherits from Foo twice, _and_ directly too -- but Bar
STILL dominates Foo, as left-first comes before depth-first.


Nothing wrong in duplicating this logic in your lookup function,
except that I'd much rather have things done ONCE whenever
feasible.  Affixing classes with an attribute, and using that
attribute's value as a key, lets us take advantage of Python's
inheritance mechanism *directly* -- because our getattr for
that attribute uses just that mechanism.  So we KNOW we
have no semantic variation in any subtle aspect, etc.  (It's
also likely to be faster, but that's a secondary issue).


Alex






More information about the Python-list mailing list