Is there a decorator to simply cache function return values?

Consider the following:

@property
def name(self):

    if not hasattr(self, '_name'):

        # expensive calculation
        self._name = 1 + 1

    return self._name

I’m new, but I think the caching could be factored out into a decorator. Only I didn’t find one like it 😉

PS the real calculation doesn’t depend on mutable values

19 Answers
19

Leave a Comment