Re: [Python-ideas] inheriting docstrings
On Fri, Jun 10, 2011 at 7:29 AM, Dj Gilcrease
Though I guess __basedocs__ mapping to [c.__doc__ for c in C.__mro__ if c != C] could be handy
Or: next(c.__doc__ for c in C.__mro__[1:] if c.__doc__) or None Right now you could do something like this: def get_basedoc(mro): return next(c.__doc__ for c in mro[1:] if c.__doc__) or None class Meta(type): __basedoc__ = property(lambda cls: get_basedoc(cls.__mro__)) But then instances don't get __basedoc__, since the metaclass is not in the MRO. To get it on instances you could do this: class C: __basedoc__ = property(lambda self: get_basedoc(self.__class__.__mro__)) But then getting that attribute on the class will give you the property object and not the docstring. I'm not sure of a way to resolve that. However, inheriting the docstring between classes is only part of the problem. You'll probably want to have the functions on a class also "inherit" their docstring from the first matching attribute of the bases on the MRO. In that case the function will not have enough information (the class isn't available to the function) to do the lookup. Instead, the class would have to do it. Here's an example: class BasedocMethod: def __init__(self, f, cls): self.f = f self.cls = cls def __getattribute__(self, name): if name == "__basedoc__": return object.__getattribute__(self, "__basedoc__") return getattr(f, name) @property def __basedoc__(self): for base in self.cls.__mro__: basefunc = base.__dict__.get(self.f.__name__) if not basefunc: continue return getattr(basefunc, "__doc__", None) return None class Meta(type): def __init__(cls, name, bases, namespace): for attrname, obj in namespace.items(): if isinstance(obj, FunctionType): setattr(cls, attrname, BasedocMethod(obj, cls)) Obviously not a perfect example, but hopefully demonstrates the idea. The whole point is that it would be nice to have a mechanism built in that makes it easy to inherit docstrings to functions, without necessarily implicitly inheriting them. The__basedoc__ idea works for that. My main motivation for this docstring inheritance is primarily for the case of abstract base classes. My implementations of those rarely have docstrings unique from that of the base class, nor do the methods. I can get around this now with metaclasses and class decorators, but it would be nice to have a little more help from the language. It would always be nice. :) -eric
_______________________________________________ Python-ideas mailing list Python-ideas@python.org http://mail.python.org/mailman/listinfo/python-ideas
participants (2)
-
Eric Snow
-
Jan Kaliszewski