doc_inherit.py 990 B

123456789101112131415161718192021222324252627282930
  1. """
  2. This is a working hack to provide inherited docstrings.
  3. The only other working way I tried would involve metaclasses.
  4. Each method to inherit a docstring is flagged using the @inherit_docstring
  5. decorator.
  6. The actual inheritance is done in the class decorator @allow_inherit_docstring,
  7. which uses the classes base-classes and its mro and copies the first docstring
  8. it finds.
  9. """
  10. def allow_inherit_docstring(cls):
  11. bases = cls.__bases__
  12. for attr, attribute in cls.__dict__.items():
  13. if hasattr(attribute, "inherit_docstring"):
  14. if not attribute.__doc__:
  15. for mro_cls in (mro_cls for base in bases for mro_cls in base.mro()
  16. if hasattr(mro_cls, attr)):
  17. doc=getattr(getattr(mro_cls,attr),'__doc__')
  18. if doc:
  19. attribute.__doc__=doc
  20. break
  21. return cls
  22. def inherit_docstring(obj):
  23. obj.inherit_docstring = True
  24. return obj