Prev: 2010 Congress on Computer Applications and Computational Science, Singapore [EI Compendex,ISTP,IEEE Xplore]
Next: Write web apps in Python?
From: Steven D'Aprano on 12 Apr 2010 02:57 On Sun, 11 Apr 2010 21:47:59 -0700, Chris Rebert wrote: > On Sun, Apr 11, 2010 at 10:46 AM, <pythonlist.calin79(a)spamgourmet.com> > wrote: >> Generally, if I want to know the inheritance tree of a class, I either >> use inspect.getmro or __bases__ >> >> However, after reading about the new numbers module / class tower in >> Python 2.6/3.0, I realized that both of these will fail to show that >> the 'float' type actually inherits from numbers.Real: > > Well, as your introspection shows, it doesn't *actually* inherit from > numbers.Real. > However, it does "implement" the numbers.Real Abstract Base Class (ABC) > and this is reported via the results of issubclass(). Basically, > `issubclass(x, y)` is no longer more-or-less just sugar for `y in > x.__mro__` due to changes that have been made to accommodate ABCs. So this is a "Consenting Adults" inheritance? If I say that MyNumber class inherits from numbers.Real, I'm responsible for making sure that MyNumber has all the appropriate methods defined by numbers.Real because it won't actually inherit any of them. Given a class C, is there some way to find out what classes issubclass(C, X) will return true for? Obviously you can get a partial list, by walking the MRO, but is there a list somewhere of which ABCs consider C a subclass? Presumably the general answer is No, because any class X could happen to have a __subclasscheck__ method that returns True when called with C. -- Steven
From: Hans Mulder on 13 Apr 2010 15:15
Steven D'Aprano wrote: > Given a class C, is there some way to find out what classes > issubclass(C, X) will return true for? Obviously you can get a partial > list, by walking the MRO, but is there a list somewhere of which ABCs > consider C a subclass? > > Presumably the general answer is No, because any class X could happen to > have a __subclasscheck__ method that returns True when called with C. New style class method __subclasses__ that returns a list of the immediate subclasses. By recursing down from object, you can make a list of all new style classes in your current interpreter. Then use issubclass to find the ones that consider themselves subclasses of C. -- HansM |