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
like this:

MySingleton.py:
---------
import threading

def mySingleton():
    if MySingleton._instance is None:
        try:
            MySingleton()
        except MySingleton, inst:
            return inst
    return MySingleton._instance

class MySingleton:
    _instance = None
    _lock = threading.RLock()

    def __init__(self):
        MySingleton._lock.acquire()
        try:
            if not MySingleton._instance is None:
                raise MySingleton._instance
            MySingleton._instance = self
            # Any other init code here
        finally:
            MySingleton._lock.release()

---------

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.)

- Ben


-----Original Message-----
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf Of Martin
Stoufer
Sent: Thursday, March 20, 2003 3:32 PM
To: [EMAIL PROTECTED]
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?
http://ads.sourceforge.net/cgi-bin/redirect.pl?micr5043en
_______________________________________________
Webware-discuss mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/webware-discuss




-------------------------------------------------------
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? 
http://ads.sourceforge.net/cgi-bin/redirect.pl?micr5043en
_______________________________________________
Webware-discuss mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/webware-discuss

Reply via email to