You can use a combination of a function and the class's __init__ to turn a
class into a singleton. It doesn't matter where you define it. Try something
if MySingleton._instance is None:
except MySingleton, inst:
_instance = None
_lock = threading.RLock()
if not MySingleton._instance is None:
MySingleton._instance = self
# Any other init code here
To access the singleton, use:
from MyModule.MySingleton import mySingleton
singleton = mySingleton()
You don't necessarily need to use an RLock to handle the locking. I like to
use them because a singleton's initialization code will often call other
methods on the singleton which require the lock, and it can be a real pain
to have multiple locks for the same object. (RLock allows the same thread to
acquire without blocking.)
[mailto:webware-discuss-admin@... Behalf Of Martin
Sent: Thursday, March 20, 2003 3:32 PM
Subject: [Webware-discuss] Writing your own singletons
Can someone in the know offer up a few pointers or links to code that
implements a singleton inside a WebKit context?
I've attempted to incorporate the instantiation of a singleton class in
the __init__ of the context, but that doesn't seem to be doing the
trick. It gets instantiated when the context is created, but
subsequently so each time a script in that dir is called as well.
* Martin C. Stoufer *
* DIDC/DSD/ITG *
* Lawrence Berkeley National Lab *
* MS 50B-2215 510-486-8662 *
This SF.net email is sponsored by: Tablet PC.
Does your code think in ink? You could win a Tablet PC.
Get a free Tablet PC hat just for playing. What are you waiting for?
Webware-discuss mailing list