Posted By

n3x on 06/01/07


python Singleton

Versions (?)

Making Daniel Brodie's singleton recipe work with keyword arguments

 / Published in: Python

The ASPN cookbook has many recipes for singletons in Python. So far, this one has been my favourite, because it is so simple and concise. However, I just ran into a brick wall when I tried to use it with a class that can be initialized with keyword arguments. This is my first draft for a solution to this problem. It's quick and dirty; please give it a glance and leave a comment if you find a problem.

  1. class Singleton(type):
  2. def __init__(self, *args, **kwds):
  3. type.__init__(self, *args, **kwds)
  4. self._instances = {}
  6. def __call__(self, *args, **kwds):
  7. sig = args + tuple(sorted(kwds.items()))
  8. if not sig in self._instances:
  9. self._instances[sig] = type.__call__(self, *args, **kwds)
  10. return self._instances[sig]

Report this snippet  


RSS Icon Subscribe to comments
Posted By: n3x on June 2, 2007

I just realized that this is probably good enough in practice if you merely want to avoid creating multiple instances for equivalent parameters, but not if you have to make absolutely sure that there are no duplicate instances (since potential keyword and positional arguments aren't disjoint sets). As it is, you can use appropriate coding conventions as a workaround.

You need to login to post a comment.