Inheriting methods' docstrings in Python

后端 未结 5 422
无人共我
无人共我 2020-12-02 16:28

I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g.,

class Swallow(object):
    def airspeed(self):
        \"\"\"R         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 17:15

    def fix_docs(cls):
        """ copies docstrings of derived attributes (methods, properties, attrs) from parent classes."""
        public_undocumented_members = {name: func for name, func in vars(cls).items()
                                       if not name.startswith('_') and not func.__doc__}
    
        for name, func in public_undocumented_members.iteritems():
            for parent in cls.mro()[1:]:
                parfunc = getattr(parent, name, None)
                if parfunc and getattr(parfunc, '__doc__', None):
                    if isinstance(func, property):
                        # copy property, since its doc attribute is read-only
                        new_prop = property(fget=func.fget, fset=func.fset,
                                            fdel=func.fdel, doc=parfunc.__doc__)
                        cls.func = new_prop
                    else:
                        func.__doc__ = parfunc.__doc__
                    break
        return cls
    

提交回复
热议问题