Singleton and C extensions

Neal Norwitz nnorwitz at gmail.com
Sat Nov 26 00:31:36 EST 2005


Emmanuel Briot wrote:
>
> I am not really good at python, but I was trying to implement the
> singleton design pattern in C, so that for instance calling the constructor
>
>    ed = Editor ("foo")
>
> would either return an existing instance of Editor currently editing
> "foo", or would create a new instance.

Hmm, if there can be more than one Editor I wouldn't call it a
singleton.
But this should do what you want:

class Editor(object):
  _cache = {}
  def __init__(self, arg):
      self._cache[arg] = self
  def __new__(cls, arg):
      if arg in cls._cache:
        return cls._cache[arg]
      return object.__new__(cls, arg)

> Has any one an example on how to do that in C, or maybe even at the
> python level itself, and I will try to adapt it ?

C is a *lot* more work and tricky too.

hth,
n




More information about the Python-list mailing list