Instance factory - am I doing this right?

Laszlo Nagy gandalf at
Wed Mar 3 18:41:37 CET 2010

This is just an interesting code pattern that I have recently used:

class CacheStorage(object):
    """Generic cache storage class."""
    def get_factory(cls,*args,**kwargs):
        """Create factory for a given set of cache storage creation 
        class CacheStorageFactory(cls):
            _construct_args = args
            _construct_kwargs = kwargs
            def __init__(self):
        return CacheStorageFactory

Then, I can create subclasses like:

class GdbmCacheStorage(CacheStorage):
    """Gdbm cache storage class.
    @param basedir: Base directory where gdbm files should be stored.
    @param basename: Base name for logging and creating gdbm files.
    def __init__(self,basedir,basename):
          ..... blablabla place initialization code here

class MemoryCacheStorage(CacheStorage):
    """In-Memory cache storage class.
    Please note that keys and values are always mashal-ed.
    E.g. when you cache an object, it makes a deep copy.
    def __init__(self):
          ..... blablabla place initialization code here

And the finally, I can create a factory that can create cache storage 
instances for storing data in gdbm in a given directory:

cache_factory = GdbmCacheStorage.get_factory("~gandalf/db","test")
print cache_factory # <class '__main__.CacheStorageFactory'>
print cache_factory()

OR I can create a factory that can create instances for storing data in 

cache_factory = MemoryCacheStorage.get_factory()
print cache_factory # <class '__main__.CacheStorageFactory'>
print cache_factory() # <__main__.CacheStorageFactory object at 0x8250c6c>

Now, here is my question. Am I right in doing this? Or are there better 
language tools to be used in Python for the same thing? This whole thing 
about creating factories looks a bit odd for me. Is it Pythonic enough?



More information about the Python-list mailing list