0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.