How to approach this?
jepler epler
jepler.lnk at lnk.ispi.net
Sun Jul 9 17:03:37 EDT 2000
You may be aware of the idiom:
class C: pass
_instance = None
def SingletonMaker():
global _instance
if _instance is None:
_instance = C()
return _instance
thus, instead of instantiating C directly, you call SingletonMaker.
However, this doesn't do the other thing you want, which is to collect
_instance when it has no more users.
Something like the following ought to work:
class UsesSingleton:
def __init__(self):
self.instance = SingletonMaker()
def __del__(self):
if sys.getrefcount(self.instance) == 3:
# _instance, self.instance, and the arg to
# sys.getrefcount
_instance = None
# When the function ends, the refcount will
# drop to 0, so self.instance will be collected
# and the next call to SingletonMaker will
# make a new one
# else, there are other references to the instance...
Of course, if someone else stores a reference to the singleton object,
this won't work..
Jeff
More information about the Python-list
mailing list