Instance factory - am I doing this right?

eb303 eric.brunel.pragmadev at gmail.com
Thu Mar 4 14:20:43 CET 2010


On Mar 3, 6:41 pm, Laszlo Nagy <gand... at shopzeus.com> wrote:
> This is just an interesting code pattern that I have recently used:
>
> class CacheStorage(object):
>     """Generic cache storage class."""
>     @classmethod
>     def get_factory(cls,*args,**kwargs):
>         """Create factory for a given set of cache storage creation
> parameters."""
>         class CacheStorageFactory(cls):
>             _construct_args = args
>             _construct_kwargs = kwargs
>             def __init__(self):
>                 cls.__init__(self,
>                     *self._construct_args,**self._construct_kwargs)
>         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
> memory:
>
> 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?
>
> Thanks,
>
>    Laszlo

Seems you try to reinvent functools:

class GdbmCacheStorage(object):
  def __init__(self,basedir,basename):
    ...
cache_factory = functools.partial(GdbmCacheStorage, "~gandalf/db",
"test")
print cache_factory()

Is it what you're after? I didn't see the point in creating a "cached
factory" for MemoryCacheStorage though, since it has no constructor
parameters to cache anyway. So doing 'cache_factory =
MemoryCacheStorage' in your example would do exactly the same thing as
what you did.

HTH
 - Eric -



More information about the Python-list mailing list