davidrpugh
davidrpugh

Reputation: 4583

How to flush cached values when dictionary changes?

I am just starting a Python package for accessing data directly from the Bureau of Economic Analysis (BEA) data API. I have two high level abstractions: Request and Results. The Request object inherits from dict and uses the requests library to access the data.

import requests


class Request(dict):

    _response = None

    base_url = 'http://www.bea.gov/api/data'

    def __init__(self, UserID, Method, ResultFormat='JSON', **params):
        required_params = {'UserID': UserID,
                           'Method': Method,
                           'ResultFormat': ResultFormat}
        required_params.update(params)
        super(Request, self).__init__(**required_params)

    @property
    def response(self):
        if self._response is None:
            self._response = requests.get(url=self.base_url, params=self)
        return self._response

Because downloading the data can be time consuming I am caching the response property. My current implementation never flushes the cache. I would like to flush the cache if any values of the dictionary change or are added/removed. Thoughts?

Upvotes: 0

Views: 97

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799210

Simply override the relevant mapping methods.

class Request(dict):
   ...
  def __setitem__(self, item, value):
    self._response = None
    return super(Request, self).__setitem__(item, value)

  def __delitem__(self, item):
    self._response = None
    return super(Request, self).__delitem__(item)

Upvotes: 2

Related Questions