from typing import Optional
import inspect


def find_method_docstring(klass, method: str) -> Optional[str]:
    """Look through a class' ancestors for the first non-empty method docstring.

    Since Python 3.5, inspect.getdoc is supposed to do exactly this. However, it doesn't seem to
    work for Cython classes.

    Examples
    --------

    >>> class Parent:
    ...
    ...     def foo(self):
    ...         '''foo method'''

    >>> class Child(Parent):
    ...
    ...     def foo(self):
    ...         ...

    >>> find_method_docstring(Child, 'foo')
    'foo method'

    """

    for ancestor in inspect.getmro(klass):
        try:
            ancestor_meth = getattr(ancestor, method)
        except AttributeError:
            break
        if doc := inspect.getdoc(ancestor_meth):
            return doc