Professional Documents
Culture Documents
The Singleton Pattern Implemented With Python Python Recipes ActiveState Code
The Singleton Pattern Implemented With Python Python Recipes ActiveState Code
The Singleton Pattern implemented with Python Python recipes ActiveState Code
TheSingletonPatternimplementedwithPython
(Pythonrecipe)byJrgenHermann
ActiveStateCode(http://code.activestate.com/recipes/52558/)
Thefollowingclassshowshowtoimplementthesingletonpattern[1]inPython.A
singletonisaclassthatmakessureonlyoneinstanceofitisevercreated.Typicallysuch
classesareusedtomanageresourcesthatbytheirverynaturecanonlyexistonce.
Python,42lines
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
c a s Snltn
ls
igeo:
""Apto snltn""
"
yhn igeo "
c a s _ip:
l s _ml
""Ipeetto o tesnltnitrae""
" mlmnain f h igeo nefc "
d f sa( ef :
e
pm sl)
""Ts mto,rtr snltni ""
" et ehd eun igeo d "
r t r i( ef
e u n d sl)
#soaefrteisac rfrne
trg o h ntne eeec
_isac = Nn
_ntne
oe
d f _ii_( ef :
e _nt_ sl)
""Cet snltnisac ""
" rae igeo ntne "
#Cekwehrw arayhv a isac
hc hte e led ae n ntne
i Snltn _isac i Nn:
f igeo. _ntne s oe
#Cet adrmme isac
rae n eebr ntne
Snltn _isac = Snltn _ip(
igeo. _ntne
igeo. _ml )
#Ts i
et t
s = Snltn )
1
igeo(
p i t i( 1 , s. pm )
rn
d s) 1 sa(
s = Snltn )
2
igeo(
p i t i( 2 , s. pm )
rn
d s) 2 sa(
Thisimplementationhidesthesingletoninterfaceinaninnerclassandcreatesexactly
oneinstanceoftheinnerclass.Theouterclassisahandletotheinnerclassand
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
1/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
delegatesanyrequeststoit.Whiletheid()ofthehandleobjectschanges,theid()ofthe
innerclasswhichimplementsthesingletonbehaviourisconstant.
Ofcourse,theinnerclassisnotREALLYhidden,likeanythinginPython.Butyouhaveto
investextraefforttobreakintothesingleton.
Thisisrelatedtothe"Automaticdelegationasanalternativetoinheritance"recipe.
[1]Gamma,Helm,etal,"DesignPatternsElementsofReusableObjectOriented
Software".AddisonWesley,1995,ISBN0201633612.
Tags:oop
13comments
HrissimirNeikov 13yearsago
RE:Singletonrightbehavior.allid'sinthesampleoutputmustbeequal!
Trythis:
c a sA
ls
:
d f S n l t n kas:
e
i g e o (ls)
i n t kas_ntne
f o ls.isac:
kas_ntne=kas)
ls.isac
ls(
r t r kas_ntne
e u n ls.isac
#sbls A
ucas
c a s BA:
ls
()
ps
as
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
2/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
b=S n l t n A
i g e o ()
c=S n l t n B
i g e o ()
d=S n l t n A
i g e o ()
p i t i()bfo)
rn
db,.o(
p i t i()cfo)
rn
dc,.o(
p i t i()cfo)
rn
dd,.o(
#Otu:
upt
76447644
930 930
76447644
930 930
76447644
930 930
mattkangas 12years,10monthsago
Asimplersingleton.Phooey,bothoftheseexamplesaretoocomplicated.:)
c a s _pm
ls
Sa:
d f _cl_( e f :
e _al_s l )
rtr sl
eun ef
S a =_pm)
pm
Sa(
d l _pm
e
Sa
Alas,thisisn'tperfect.IfforsomereasonyouneedtosubclassSpam,youobviouslycan't.
ButIthinkthisissufficientformostpeople'sneeds.
SincePythondoesn'thaveanynotionofclass/staticmethods,itisn'tpossibletobuild
singletons"therightway".Everyworkablesolutionwillbeacompromiseofsomesort.
mattkangas 12years,10monthsago
Obfuscatedsingleton.ps:Ofcoursethisispossibletoo...
c a sS a :
ls
pm
d f _cl_( e f :
e _al_s l )
rtr sl
eun ef
S a =S a (
pm
p m)
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
3/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
RowlandSmith 12years,8monthsago
Singletonexample.
c a sT s S n l t n:
ls
etigeo
#otnu iiilzto..
Cniie ntaiain.
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
4/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
Thissingletonimplementationdrawsfrom'staticmethod/classmethod'
examplesbyThomasHellerandClarkEvans.
SbastienBigaret 11years,11monthsago
Subclassingispossible,butugly!Inheritanceispossibleandcanbedocumentedas
suchifyouusesuchanidiomtoimplementtheSingleton.
c a s E g ( p m _cas_:#Teoiia casi silaalbe
ls
g s S a ._ls_)
h rgnl ls s tl vial
d f _cl_( e f :
e
_al_s l )
rtr sl
eun ef
E g =g s)
g sE g (
#Tee3lns
hs
ie
#sol b
hud e
#rpiae
elctd
SbastienBigaret 11years,11monthsago
Smallcorrection.Thisdoesonlyworkifyoucall'getInstance()'beforetheconstructorif
not,youwillgetamuchdifferentinstancesasyouwishuntil'getInstance()'getcalled:
>>f r ii rne3:
> o
n ag()
>> p i t ' %'T s S n l t n )
>
r n > s% e t i g e o (
>&tT s S n l t n isac a 0815cg;
l; e t i g e o
ntne t x1f5&t
>&tT s S n l t n isac a 0826cg;
l; e t i g e o
ntne t x149&t
>&tT s S n l t n isac a 081acg;
l; e t i g e o
ntne t x1ee&t
Ifyouwanttomakesurethattheconstructorisnotcalledmorethanonce,
'TestSingleton.__init__'shouldread:
d f _ii_( e f :
e
_nt_s l )
i n t T s S n l t n isac = N n :
f o
e t i g e o .ntne = o e
r i e R n i e r o ,'nyoeisac o TsSnltni alwd'
as
u t m E r r Ol n ntne f etigeo s loe!
T s S n l t n isac= e f
e t i g e o .ntnes l
(lastlineadded)
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
5/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
ChristianMeyer 7years,5monthsago
Mucheasiersolution.Ifoundsomeofthepreviouslymentionedideasabittoo
complicated.Here'smyimplementation:
c a s _igeo( b e t :
ls
Snltno j c )
d f _ii_( e f :
e _nt_s l )
_igeo =_igeo(
snltn
Snltn)
d f S n l t n ) r t r _igeo
e
i g e o (: e u n snltn
=====
>>f o snltni p r S n l t n
> r m igeo m o t i g e o
>>s =S n l t n )
> 1
igeo(
>>s =S n l t n )
> 2
igeo(
>>s.ntne
> 1isac
'ntnea -26920
Isac t 12652'
>>s.ntne
> 2isac
'ntnea -26920
Isac t 12652'
>>s = s
> 1 = 2
Tu
re
MarcSantiago 6years,5monthsago
Singletonswithinheritance.
c a sS n l t no j c )
ls
i g e o (b e t:
_snl =N n #teoe tu Snltn
_ige
oe
h n, re igeo
d f _nw_casye *rs *kag)
e
_e_(lstp, ag, *wrs:
6/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
p i t s l .aei( e f ,yes l )
rn
e f nm,ds l )tp( e f
c a sS b i g e o (i g e o )
ls
u s n l t nS n l t n:
ps
as
i _nm_ = "_an_:
f _ae_ = _mi_"
o =S n l t n 'o'
1
i g e o (fo)
o.ipa(
1dsly)
o =S n l t n 'a'
2
i g e o (br)
o.ipa(
2dsly)
o =S b i g e o (foa'
3
u s n l t n 'obr)
o.ipa(
3dsly)
o =S b i g e o (bro'
4
u s n l t n 'afo)
o.ipa(
4dsly)
p i t '1=o:,1= o
rn
o
2'o = 2
p i t '1=o:,1= o
rn
o
3'o = 3
p i t '3=o:,3= o
rn
o
4'o = 4
p i t '1i asnltn'iisac(1S n l t n
rn
o s
igeo?,sntneo, i g e o )
p i t '3i asnltn'iisac(3S n l t n
rn
o s
igeo?,sntneo, i g e o )
p i t '1i asbigeo?,sntneo, u s n l t n
rn
o s
usnltn'iisac(1S b i g e o )
p i t '3i asbigeo?,sntneo, u s n l t n
rn
o s
usnltn'iisac(3S b i g e o )
YairChuchem 6years,1monthago
goodone.youshouldputthatoneasarecipe.
AlanFelice 6yearsago
Andwhataboutthreads?GivenimplementationsofSingletonpatternaren'tthreadsafe.
Somemorestuffisneededtoreachthatpoint.Somethinglikethe
followingshouldbeused:
c a sM S n l t n l s (b e t:
ls
y i g e o C a so j c )
''mlmn Pten SNLTN'
'Ipeet atr: IGEO''
_lcOj=tra.loaelc( #lc ojc
_okb
hedalct_ok)
ok bet
_isac =N n
_ntne
o e #teuiu isac
h nqe ntne
d f _nw_cs *rs *krs:
e _e_(l, ag, *ag)
r t r csgtntnecs *rs *krs
e u n l.eIsac(l, ag, *ag)
d f _ii_( e f :
e _nt_s l )
ps
as
d f gtntnecs *rs *krs:
e eIsac(l, ag, *ag)
''ttcmto t hv arfrnet *TEUIU* isac''
'Sai ehd o ae
eeec o *H NQE* ntne'
#Ciia scinsat
rtcl eto tr
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
7/8
28/4/2014
The Singleton Pattern implemented with Python Python recipes ActiveState Code
cs_lcOjaqie)
l._okb.cur(
ty
r:
i cs_isac i N n :
f l._ntne s o e
#(oeecpinmyb trw..
Sm xeto a e hon.)
#Iiilz *teuiu* isac
ntaie *h nqe* ntne
cs_isac =o j c ._e_(l,*rs *krs
l._ntne
b e t _nw_cs ag, *ag)
''ntaieojc *hr*,a yuwudd i _ii_(..'
'Iiilz bet *ee* s o ol o n _nt_).''
fnly
ial:
#Ciia scined
rtcl eto n
r t r cs_isac
e u n l._ntne
gtntne=casehdgtntne
eIsac
lsmto(eIsac)
GaryRobinson 4years,9monthsago
There'saversionthat'sbeenevolvingforabout5yearsat
http://www.garyrobinson.net/2004/03/python_singleto.html.It'sprettycompleteandhas
benefittedfromafairamountoffeedbackandsuggestionsatthatlocation.It'sthreadsafe
andincludesunittests.
Itriedtopostithere,butevenleavingouttheunittests,it'slongerthanthe3000charlimit
inthiscommentarea.
GaryRobinson 4years,9monthsago
Oops,thesourceatthelinkabovewasaccidentallyanoutofdateversionuntilnow(without
thethreadsafetyandsomeotherimprovements)untilnow.Fixednow.
Reorx 1year,6monthsago
Code:
c a sS n l t no j c )
ls
i g e o (b e t:
@lsmto
casehd
d f isac(l,*rs *kg)
e ntnecs ag, *ws:
i n t hstrcs "isac":
f o aat(l, _ntne)
cs_ntne=cs*rs *kg)
l.isac
l(ag, *ws
r t r cs_ntne
e u n l.isac
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/
8/8