singleton objects with decorators

Uwe Mayer merkosh at hadiko.de
Tue Apr 12 12:58:32 EDT 2005


Tuesday 12 April 2005 18:51 pm Michele Simionato wrote:

> Uhm? If I pass different parameters I want to have
> different instances. The Singleton behaviour is recovered
> only when I pass always the same arguments, in
> particular when I pass 0-arguments:
> 
>>>> class Foobar:
> ...     __metaclass__ = Memoize
> ...
>>>> Foobar()
> <__main__.Foobar object at 0xb7defbcc>
>>>> Foobar()
> <__main__.Foobar object at 0xb7defbcc>
>>>> Foobar()
> <__main__.Foobar object at 0xb7defbcc>
> 
> Of course if for Singleton you mean "whatever I pass
> to the constructor it must always return the same
> instance" then this pattern is not a Singleton.
> This is why I call it memoize ;)

:)

I guess it depends on what you want to do with the instance and the
constructor, wether it satisfies the condition to be a "singleton":

If you pass i.e. the timestamp of object creation in the constructor, or the
class name that instanciates the object, a memoized implementation would
not suffice.

On the other hand if you need parameterized implementations of a singleton,
i.e. for each colour 'red', 'green', 'blue' - then a memoized
implementation would be better.

Uwe



More information about the Python-list mailing list