Test the MiniFridge() class


In [1]:
import fridge

Create a MiniFridge with a 1-minute default timer


In [2]:
mf = fridge.MiniFridge(minutes=1)
mf


Out[2]:
<fridge.MiniFridge at 0x106426d68>

What's in the MiniFridge?


In [3]:
mf.keys()


Out[3]:
dict_keys([])

In [4]:
# Put some things in the MiniFridge
mf.put('spam',42,expire=False)  # spam will outlast us all
mf.put('eggs',2,seconds=2)      # eggs expires after 2 seconds
mf['beer'] = 100                # beer expires after default time
mf.keys()


Out[4]:
dict_keys(['spam', 'beer', 'eggs'])

In [5]:
# Get things out of the MiniFridge.
for key in mf.keys():
    print(key,mf[key])


spam 42
beer 100
eggs 2

Wait a few seconds and see if anything expires


In [6]:
for x in ['spam','eggs','beer']:
    print( "%s in fridge? %s" % (x, x in mf) )


spam in fridge? True
eggs in fridge? True
beer in fridge? True

In [7]:
import time
time.sleep(2)

In [8]:
for x in ['spam','eggs','beer']:
    print( "%s in fridge? %s" % (x, x in mf) )


spam in fridge? True
eggs in fridge? False
beer in fridge? True

In [9]:
# Throw out spam. Is anything left?
del mf['spam']
mf.keys()


Out[9]:
dict_keys(['beer'])

Other methods


In [10]:
# Use get() to avoid raising a KeyError when a key is bad
mf.get('spam',default='No spam for you.')


Out[10]:
'No spam for you.'

In [11]:
# Put some Champagne in the fridge
mf['Champagne'] = 'Bubbles!'
mf.keys()


Out[11]:
dict_keys(['beer', 'Champagne'])

In [12]:
# Pop the Champagne
mf.pop('Champagne',default='Pas de champagne pour vous.')


Out[12]:
'Bubbles!'

In [13]:
# Is there any more Champagne?
'Champagne' in mf


Out[13]:
False

In [14]:
# Delete all contents of the fridge
mf.clear()
mf.keys()


Out[14]:
dict_keys([])

Show help()


In [15]:
help(fridge.MiniFridge)


Help on class MiniFridge in module fridge:

class MiniFridge(builtins.object)
 |  A MiniFridge is like a dictionary, but with 2 extra rules:
 |  
 |  1. If another thread is using the fridge, then wait your turn.
 |  2. If you see something past its expiration date, then throw it out.
 |  
 |  Some MiniFridge methods allow users to set a countdown timer.
 |  These timers are set using keyword arguments for datetime.timedelta:
 |  weeks, days, hours, minutes, seconds, microseconds, milliseconds
 |  
 |  Examples:
 |  
 |  mf = MiniFridge(minutes=1)      # Make a MiniFridge with 1-minute timer
 |  
 |  mf.put('spam',42,expire=False)  # Put spam in mf. It never expires
 |  mf.put('eggs',2,seconds=2)      # Put eggs in mf. It expires in 2 seconds.
 |  mf['beer'] = 100                # Put beer in mf. It expires in 1 minute.
 |  
 |  mf['spam']                      # Get value for key 'spam'
 |  mf.get('eggs',default='Nope')   # Get value without raising KeyError if key is bad
 |  mf.pop('beer',default=None)     # Pop value without raising KeyError if key is bad
 |  
 |  mf.keys()                       # Delete any bad items. Return the good keys.
 |  mf.purge()                      # Delete any expired (key,value) pairs
 |  mf.clear()                      # Delete everything 
 |      
 |  Caution: There are no built-in limits to size or number of elements.
 |  Caution: Not all dictionary methods have been implemented yet.
 |  Caution: Not well-tested yet, especially with multi-threading.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key)
 |      Magic function for answering "x in MiniFridge" questions.
 |      If key is not found, then return False.
 |      If key is found but has expired, then throw it out! Return False.
 |      If key is found and has not expired, then return True.
 |  
 |  __delitem__(self, key)
 |      Delete (key,value) pair
 |  
 |  __getitem__(self, key)
 |      Get a value from the MiniFridge dictionary-style.
 |      If key is not found, this will throw a KeyError.
 |      If key is found but expired, this with throw a KeyError.
 |  
 |  __init__(self, **kwargs)
 |      Initialize an empty dictionary with a lock and optional default timer.
 |      Use timedelta kwargs to set default timer. Stored items will expire
 |      after this much time unless specified otherwise. If no **kwargs,
 |      then timer is set to roughly 100 years.
 |  
 |  __len__(self)
 |      How many items are in the fridge?
 |  
 |  __setitem__(self, key, value)
 |      Put a (key,value) pair in the MiniFridge dictionary-style
 |  
 |  clear(self)
 |      Delete all (key,value) pairs
 |  
 |  get(self, key, default=None)
 |      Like __getitem__(), but does not raise a KeyError if key is bad.
 |      Returns default value instead.
 |  
 |  keys(self)
 |      Throw out anything that has expired.
 |      Return whatever keys are left.
 |  
 |  pop(self, key, default=None)
 |      Pop a value: return it and delete it. Like get(), but
 |      deletes (key,value) whether or not it has expired.
 |  
 |  purge(self)
 |      Throw out anything that has expired
 |  
 |  put(self, key, value, expire=True, **kwargs)
 |      Put a (key,value) pair in the MiniFridge with optional timer.
 |      By default, it will expire after default_timer elapses.
 |      To choose a different lifetime, use timedelta kwargs.
 |      To set lifetime to infinity, use expire=False.
 |  
 |  set_expiration(self, key, expiration_time)
 |      Instead of a countdown timer, set a specific expiration date.
 |      expiration_time should be a datetime object.
 |      Will raise a KeyError if key is not found.
 |  
 |  values(self)
 |      Throw out anything that has expired.
 |      Return whatever values are left.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  is_past(t)
 |      Convenience function for figuring out if something has expired
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)