Esempio n. 1
0
def overridden(method):
    """
    :return: True if ``method`` overrides some method with the same
    name in a base class.  This is typically used when defining
    abstract base classes or interfaces, to allow subclasses to define
    either of two related methods:

        >>> class EaterI:
        ...     '''Subclass must define eat() or batch_eat().'''
        ...     def eat(self, food):
        ...         if overridden(self.batch_eat):
        ...             return self.batch_eat([food])[0]
        ...         else:
        ...             raise NotImplementedError()
        ...     def batch_eat(self, foods):
        ...         return [self.eat(food) for food in foods]

    :type method: instance method
    """
    # [xx] breaks on classic classes!
    if isinstance(method, types.MethodType) and compat.get_im_class(method) is not None:
        name = method.__name__
        funcs = [cls.__dict__[name]
                 for cls in _mro(compat.get_im_class(method))
                 if name in cls.__dict__]
        return len(funcs) > 1
    else:
        raise TypeError('Expected an instance method.')
Esempio n. 2
0
def overridden(method):
    """
    :return: True if ``method`` overrides some method with the same
    name in a base class.  This is typically used when defining
    abstract base classes or interfaces, to allow subclasses to define
    either of two related methods:

        >>> class EaterI:
        ...     '''Subclass must define eat() or batch_eat().'''
        ...     def eat(self, food):
        ...         if overridden(self.batch_eat):
        ...             return self.batch_eat([food])[0]
        ...         else:
        ...             raise NotImplementedError()
        ...     def batch_eat(self, foods):
        ...         return [self.eat(food) for food in foods]

    :type method: instance method
    """
    # [xx] breaks on classic classes!
    if isinstance(
            method,
            types.MethodType) and compat.get_im_class(method) is not None:
        name = method.__name__
        funcs = [
            cls.__dict__[name] for cls in _mro(compat.get_im_class(method))
            if name in cls.__dict__
        ]
        return len(funcs) > 1
    else:
        raise TypeError('Expected an instance method.')