Preserve original docstring in cachedproperty

Set the __doc__ attribute on the original
docstring so that the docstring is preserved
and visible to tooling like sphinx and epydoc.

Slightly simply __get__ and remove a line of code
This commit is contained in:
Brant Watson 2017-01-13 09:34:32 -06:00
parent 87ac574fa4
commit 4abe46233f
2 changed files with 6 additions and 3 deletions

View File

@ -648,15 +648,14 @@ class cachedproperty(object):
allows the cache to be cleared with :func:`delattr`, or through allows the cache to be cleared with :func:`delattr`, or through
manipulating the object's ``__dict__``. manipulating the object's ``__dict__``.
""" """
def __init__(self, func): def __init__(self, func):
self.__doc__ = getattr(func, '__doc__')
self.func = func self.func = func
def __get__(self, obj, objtype=None): def __get__(self, obj, objtype=None):
if obj is None: if obj is None:
return self return self
value = self.func(obj) value = obj.__dict__[self.func.__name__] = self.func(obj)
setattr(obj, self.func.__name__, value)
return value return value
def __repr__(self): def __repr__(self):

View File

@ -270,6 +270,7 @@ def test_cachedproperty():
@cachedproperty @cachedproperty
def useful_attr(self): def useful_attr(self):
"""Useful DocString"""
return self.expensive_func() return self.expensive_func()
prop = Proper() prop = Proper()
@ -280,6 +281,9 @@ def test_cachedproperty():
assert prop.useful_attr == 1 assert prop.useful_attr == 1
assert prop.expensive_func.call_count == 1 assert prop.expensive_func.call_count == 1
# Make sure original DocString is accessible
assert Proper.useful_attr.__doc__ == "Useful DocString"
prop.useful_attr += 1 # would not be possible with normal properties prop.useful_attr += 1 # would not be possible with normal properties
assert prop.useful_attr == 2 assert prop.useful_attr == 2