Package lastfm :: Package mixins :: Module cacheable
[hide private]
[frames] | no frames]

Source Code for Module lastfm.mixins.cacheable

 1  #!/usr/bin/env python 
 2   
 3  __author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>" 
 4  __version__ = "0.2" 
 5  __license__ = "GNU Lesser General Public License" 
 6   
 7  try: 
 8      from threading import Lock 
 9  except ImportError: 
10      from dummy_threading import Lock 
11 12 -class Cacheable(object):
13 registry = {} 14 _lock = Lock() 15
16 - def __new__(cls, *args, **kwds):
17 subject = None 18 if 'subject' in kwds and not cls.__name__.startswith('Weekly'): 19 subject = kwds['subject'] 20 #del kwds['subject'] 21 22 if 'bypass_registry' in kwds: 23 del kwds['bypass_registry'] 24 inst = object.__new__(cls) 25 inst.init(*args, **kwds) 26 return inst 27 28 key = cls._hash_func(*args, **kwds) 29 if subject is not None: 30 key = (hash(subject), key) 31 32 Cacheable._lock.acquire() 33 try: 34 inst, already_registered = Cacheable.register(object.__new__(cls), key) 35 if not already_registered: 36 inst.init(*args, **kwds) 37 finally: 38 Cacheable._lock.release() 39 return inst
40 41 @staticmethod
42 - def register(ob, key):
43 if not ob.__class__ in Cacheable.registry: 44 Cacheable.registry[ob.__class__] = {} 45 if key in Cacheable.registry[ob.__class__]: 46 ob = Cacheable.registry[ob.__class__][key] 47 #print "already registered: %s" % repr(ob) 48 return (ob, True) 49 else: 50 #print "not already registered: %s" % ob.__class__ 51 Cacheable.registry[ob.__class__][key] = ob 52 return (ob, False)
53