Python - compute a property only once and use the result several times (different approaches)

I try to use the result of a class method several times, without requiring the large calculations needed to get the result.

I see the following options, which ones, in your opinion, are correct or more Pythonic?

What are the advantages and disadvantages of each?

Try / Except:

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    def new_method(self):
        try:
            return self._new_property
        except AttributeError:
            # do some heavy calculations
            return self._new_property

lru_cache approach:

from functools import lru_cache

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    @lru_cache()
    def new_method(self):
        # do some heavy calculations
        return self._new_property

Django cache_property approach:

from django.utils.functional import cached_property

class Test:
    def __init__(self, *args):
        # do stuff

    @cached_property
    def new_method(self):
        # do some heavy calculations
        return self._new_property
+4
source share
1 answer
  • Try/except , , ? , , .

  • lru_cache , lru, , .

  • Django cache_property , , . werkzeug ( Flask ), , , , .

+1

Source: https://habr.com/ru/post/1681394/


All Articles