4
\$\begingroup\$

I was recently working on some python where I was working with multiple inheritance and mixins and stuff like that, and I wanted to inherit docstrings for specific functions, from specific parents (particularly in the case of the mixins). Anyways, I came up with this recipe for inheriting docstrings and was hoping for some feedback on the strategy I used.

def get_doc(func, class_, check_self=True):
    check_self = int(not check_self)
    for parent in class_.__mro__[check_self:]:
        doc = parent.__dict__.get(func.__name__, None).__doc__
        if doc is not None:
            return doc
    return ""

def prepend(parent, child):
    return f"{parent}\n{child}"

def doc_inherit(class_, check_self=True, combine=prepend):
    def decorator(func):
        doc = get_doc(func, class_, check_self)
        func.__doc__ = combine(doc, "" if func.__doc__ is None else func.__doc__
        return func
    return decorator

Usage:

In [1]: class A:
   ...:     def instance_method(self, *args):
   ...:         "A.instance_method"
   ...:         pass
   ...:

In [2]: class B(A):
   ...:     @doc_inherit(A)
   ...:     def instance_method(self, *args):
   ...:         "B.instance_method"
   ...:         pass
   ...:

In [3]: help(B.instance_method)
Help on function instance_method in module __main__:

instance_method(self, *args)
    A.instance_method
    B.instance_method


In [4]: help(B().instance_method)
Help on method instance_method in module __main__:

instance_method(*args) method of __main__.B instance
    A.instance_method
    B.instance_method

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.