Liuw's Thinkpad

想要赢就先学会输,想要成功就先学会失败

Archive for the ‘singleton’ tag

Python Singleton Pattern Implementation

without comments

There are three ways to get this job done.

1 Module Implementation

The easiest implementation is to use a module scope variable. Module is persistent and shared by all references through its life time, no matter how it is renamed or modified.

See this [stackoverflow post on Python singleton]. Xen Xend makes use of this Python feature, which exposes a moudule function as interface to singleton class.

2 Class Implementation

The second implemention is class implementation, it’s not so convenient because Python does not support static variable itself. It certainly requires some tricks to get this job done.

According to this [ActiveState recipe 52558], it’s all about create exactly one instance of some class. But this is not so convient cause it uses automatic delegation.

3 Function Argument Default Value Implementation

Also another trick. The default value of a function argument is initialized only once and persistent. See the following example.

def f(x, l=[]):
    l.append(x)
    return l

This is least recommended.

Written by liuw

March 13th, 2010 at 11:27 pm