Brain Dead Singleton

Robin Becker robin at SPAMREMOVEjessikat.fsnet.co.uk
Sat Jun 5 12:43:40 CEST 2004


Colin Brown wrote:
> "Kamilche" <klachemin at home.com> wrote in message
> news:889cbba0.0406041333.10402447 at posting.google.com...
> 
>>I looked on this newsgroup, and saw all the problems with making a
>>Singleton class with Python.
> 
> 
> Whenever I want a singleton "class", I just use a module with functions and
> global variables. Modules only import once.
> 
> Colin Brown
> PyNZ
> 
> 
> 
should often work, but this illustrates how it can go wrong

##################
f=open('my_singleton_module.py','w')
f.write('''a=0
def incr(i):
	global a
	oa = a
	a+=i
	return oa
''')
f.close()

import my_singleton_module as inst0
print inst0.a
inst0.incr(5)
print inst0.a
import sys
del sys.modules['my_singleton_module']
import my_singleton_module as inst1
print inst1.a
##################

so if sys.modules gets interfered with approriately, your singleton can 
start breeding.
-- 
Robin Becker



More information about the Python-list mailing list