MFB
MFB

Reputation: 19787

Efficient property setting within Python class

I have a class which queries a database for it properties. As you can see in the code below, I need to set a candidates property, but then set a prime property based on the candidates property. However, I want to avoid querying the database twice. What's the best way to go about this?

class Event(object):
    def __init__(self):
        pass

    @property
    def candidates(self):
        # get candidates from db
        return query_result

    @property
    def prime(self):
        # get prime based on complex logic with candidates.  Simplified eg:
        return self.candidates[0]  # hits db again :(

If I set self.prime within the candidates definition but then call prime before candidates, I will get an error. What's the best way to do this?

Upvotes: 0

Views: 60

Answers (1)

Jonathan Eunice
Jonathan Eunice

Reputation: 22443

Cache the result in a private variable.

class Event(object):
    def __init__(self):
        self._candidates = None

    @property
    def candidates(self):
        # get candidates from db
        self._candidates = query_result
        return query_result

    @property
    def prime(self):
        # get prime based on complex logic with candidates.  Simplified eg:
        return self._candidates[0] 

This assumes you want to hit the database / refresh the data each time the candidates property is accessed. If the candidates property is not so dynamic, then you can front-end the query. Like so:

    @property
    def candidates(self):
        if self._candidates is None:
            # get candidates from db
            self._candidates = query_result
        return self._candidates

Upvotes: 1

Related Questions