From 4abe46233fc1cdc6c4d7e2182699cb06a92f6b32 Mon Sep 17 00:00:00 2001 From: Brant Watson Date: Fri, 13 Jan 2017 09:34:32 -0600 Subject: [PATCH] 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 --- boltons/cacheutils.py | 5 ++--- tests/test_cacheutils.py | 4 ++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/boltons/cacheutils.py b/boltons/cacheutils.py index 9d6156a..d8f3620 100644 --- a/boltons/cacheutils.py +++ b/boltons/cacheutils.py @@ -648,15 +648,14 @@ class cachedproperty(object): allows the cache to be cleared with :func:`delattr`, or through manipulating the object's ``__dict__``. """ - def __init__(self, func): + self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, objtype=None): if obj is None: return self - value = self.func(obj) - setattr(obj, self.func.__name__, value) + value = obj.__dict__[self.func.__name__] = self.func(obj) return value def __repr__(self): diff --git a/tests/test_cacheutils.py b/tests/test_cacheutils.py index d325df9..9129c8b 100644 --- a/tests/test_cacheutils.py +++ b/tests/test_cacheutils.py @@ -270,6 +270,7 @@ def test_cachedproperty(): @cachedproperty def useful_attr(self): + """Useful DocString""" return self.expensive_func() prop = Proper() @@ -280,6 +281,9 @@ def test_cachedproperty(): assert prop.useful_attr == 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 assert prop.useful_attr == 2