singleton decorator

Georg Brandl g.brandl-nospam at gmx.net
Tue Aug 8 06:46:37 EDT 2006


Andre Meyer wrote:
> While looking for an elegant implementation of the singleton design 
> pattern I came across the decorator as described in PEP318 
> <http://www.python.org/dev/peps/pep-0318/>.
> Unfortunately, the following does not work, because decorators only work 
> on functions or methods, but not on classes.
> 
> def singleton(cls):
>     instances = {}
>     def getinstance():
>         if cls not in instances:
>             instances[cls] = cls()
> 
>         return instances[cls]
>     return getinstance
> 
> @singleton
> class MyClass:
>     ...
> 
> 
> Am I missing something here? What is the preferred pythonic way of 
> implementing singleton elegantly?

You can always use the syntax the decorator replaces:

class MyClass:
     ...
MyClass = singleton(MyClass)

But there are better ways, and maybe you don't even need a singleton.
See the Python Cookbook.

Georg



More information about the Python-list mailing list