In section 2 of the Udemy course on Intermediate Python we had some homework… to write out the code to store some cached values to a dictionary and have methods to set new values, get values, delete specific values and flush the cache.

My solution was the following:

class Memcache:
    def __init__(self):
        self.CACHE = {}

    def set(self, key, value):
        self.key = key
        self.value = value
        self.CACHE[key] = value
        return key, value

    def get(self, key):
        self.key = key
        return self.CACHE[key]

    def delete(self, key):
        self.key = key
        del self.CACHE[key]

    def flush(self):
        self.CACHE.clear()

def test_memcache():
    m = Memcache()
    print("set a: " + str(m.set('a', '1')))
    print("set b: " + str(m.set('b','2')))
    print(m.CACHE)
    print(m.get('b'))
    m.delete('b')
    m.flush()
    print("Cache After Flush: " + str(m.CACHE))

test_memcache()

The test method (test_memcache()) will return:
>> set a: (‘a’,’1′)
>> set b: (‘b’,’2′)
>> {‘b’: ‘2’, ‘a’: ‘1’}
>> 2
>> Cache After Flush: {}

Leave a Reply

Your email address will not be published. Required fields are marked *