Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #37688

Re: finding abc's

From Peter Otten <__peter__@web.de>
Subject Re: finding abc's
Date 2013-01-25 20:08 +0100
Organization None
References <766ec7eb-ab43-4c17-8073-3a0e6a8b89ea@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1052.1359140888.2939.python-list@python.org> (permalink)

Show all headers | View raw


lars van gemerden wrote:

> Hi all,
> 
> i was writing a function to determine the common base class of a number
> classes:
> 
> def common_base(classes):
>     if not len(classes):
>         return None
>     common = set(classes.pop().mro())
>     for cls in classes:
>         common.intersection_update(cls.mro())
>     while len(common) > 1:
>         cls1 = common.pop()
>         cls2 = common.pop()
>         if issubclass(cls1, cls2):
>             common.add(cls1)
>         elif issubclass(cls2, cls1):
>             common.add(cls2)
>     return common.pop()
> 
> and ran common_base(int, float), hoping to get numbers.Number.
> 
> this did not work because abstract base classes are not always in the
> mro() of classes.
> 
> My question is: is there a way to obtain the abc's of a class or otherwise
> a way to make the function above take abc's into account (maybe via a
> predefined function)?

The abstract base classes may run arbitrary code to determine the subclass 
relationship:
 
>>> from abc import ABCMeta
>>> import random
>>> class Maybe(metaclass=ABCMeta):
...     @classmethod
...     def __subclasshook__(cls, C):
...             print("processing", C)
...             return random.choice((False, True))
... 
>>> isinstance(1.1, Maybe)
processing <class 'float'>
True
>>> isinstance(1.1, Maybe)
True
>>> isinstance(1, Maybe)
processing <class 'int'>
False
>>> issubclass(float, Maybe)
True

You'd have to check every pair of classes explicitly and might still miss 
(for example) numbers.Number as the module may not have been imported. 

I think you are out of luck.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 09:40 -0800
  Re: finding abc's Ian Kelly <ian.g.kelly@gmail.com> - 2013-01-25 12:04 -0700
    Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 12:05 -0800
    Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 12:05 -0800
  Re: finding abc's Peter Otten <__peter__@web.de> - 2013-01-25 20:08 +0100
    Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 12:08 -0800
      Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 16:48 -0800
      Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 16:48 -0800
    Re: finding abc's lars van gemerden <lars@rational-it.com> - 2013-01-25 12:08 -0800

csiph-web