You are on page 1of 8

28/4/2014

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 )

#Soeisac rfrnea teol mme i tehnl


tr ntne eeec s h ny ebr n h ade
sl. _it_ 'Snltn_ntne] = Snltn _isac
ef _dc_[ _igeo_isac'
igeo. _ntne
d f _gttr_ sl, at)
e _eat_( ef tr :
""Dlgt acs t ipeetto ""
" eeae ces o mlmnain "
r t r gttr sl. _ntne at)
e u n eat( ef _isac, tr
d f _sttr_ sl, at, vle :
e _eat_( ef tr au)
""Dlgt acs t ipeetto ""
" eeae ces o mlmnain "
r t r sttr sl. _ntne at, vle
e u n eat( ef _isac, tr au)

#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(

#Sml otu,tescn (ne)i i cntn:


ape upt h eod inr d s osat
#87648728
128 166
#86588728
188 166

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
:

#atiuekont fnto Snltn


trbt nw o ucin igeo
_ntne=N n
isac
oe
d f fos l )
e o( e f :
r t r i( e f
e u n ds l )

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

#Cet acasvral ta wl hl arfrne


rae
ls aibe ht il od
eeec
#t tesnl isac o TsSnltn
o h ige ntne f etigeo.
isac =N n
ntne
oe

#Dfn ahle casta wl oerd te_cl__


eie
epr ls ht il vrie h _al_
#mto i odrt poieafcoymto frTsSnltn
ehd n re o rvd
atr ehd o etigeo.
c a sT s S n l t n e p r:
ls
etigeoHle
d f _cl_(s l ,*rs *k ):
e
_al_ e f ag, *w

#I a isac o TsSnltnde nteit


f n ntne f etigeo os o xs,
#cet oeadasg i t TsSnltnisac.
rae n n sin t o etigeo.ntne
i T s S n l t n isac i N n :
f e t i g e o .ntne s o e
o j c =T s S n l t n )
bet
etigeo(
T s S n l t n isac =o j c
e t i g e o .ntne
bet

#Rtr TsSnltnisac,wihsol cnan


eun etigeo.ntne hc hud oti
#arfrnet teol isac o TsSnltn
eeec o h ny ntne f etigeo
#i tesse.
n h ytm
r t r T s S n l t n isac
e u n e t i g e o .ntne

#Cet acaslvlmto ta ms b cle t


rae
ls ee ehd ht ut e ald o
#gttesnl isac o TsSnltn
e h ige ntne f etigeo.
gtntne=T s S n l t n e p r )
eIsac
etigeoHle(

#Iiilz a isac o teTsSnltncas


ntaie n ntne f h etigeo ls.
d f _ii_(s l ):
e _nt_ e f

#Otoal,yucudg abtfrhrt gaate


pinly o ol o
i ute o urne
#ta n oecetdmr ta oeisac o TsSnltn
ht o n rae oe hn n ntne f etigeo:
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!

#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

#Ts ti ipeetto o teSnltnpten Alo te


et hs mlmnain f h igeo atr. l f h
#rfrne pitdotsol hv tesm ades
eeecs rne u hud ae h ae drs.
f r ii rne 1 ):
o
n ag( 0
p i t T s S n l t n gtntne)
rn
e t i g e o .eIsac(

#Ti cl sol rieaRniero idctn


hs al hud as
utmErr niaig
#ta asnl isac o TsSnltnarayeit.
ht
ige ntne f etigeo led xss
T s S n l t n)
etigeo(

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 )

#js frtesk o ifrain


ut o h ae f nomto
s l .ntne="ntnea %"%s l ._ah_)
e f isac
Isac t d
e f _hs_(

_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:

#Cekt sei a_snl eit arayfrti cas


hc o e f
_ige xss led o hs ls
#Cmaecastpsisedo js loigfrNn s
opr ls ye nta f ut okn o oe o
#ta sblse wl cet teron_snl ojcs
ht ucass il rae hi w _ige bet
i casye! tp(lstp._ige:
f lstp = yecasye_snl)
casye_snl =o j c ._e_(lstp,*rs *kag)
lstp._ige
b e t _nw_casye ag, *wrs
r t r casye_snl
e u n lstp._ige
d f _ii_( e f nm= o e :
e
_nt_s l ,aeN n )
s l .ae=nm
e f nm
ae
d f dslys l )
e
ipa( e f :
http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/

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:

# Ei fo ciia scinwaee hpes


xt rm rtcl eto htvr apn
cs_lcOjrlae)
l._okb.ees(

#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

You might also like