<div class="gmail_quote">On 24 September 2012 00:14, Mark Lawrence <span dir="ltr"><<a href="mailto:breamoreboy@yahoo.co.uk" target="_blank">breamoreboy@yahoo.co.uk</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Purely for fun I've been porting some code to Python and came across the singletonMap[1].  I'm aware that there are loads of recipes on the web for both singletons e.g.[2] and immutable dictionaries e.g.[3].  I was wondering how to combine any of the recipes to produce the best implementation, where to me best means cleanest and hence most maintainable.  I then managed to muddy the waters for myself by recalling the Alex Martelli Borg pattern[4].  Possibly or even probably the latter is irrelevant, but I'm still curious to know how you'd code this beast.<br>
</blockquote><div><br></div><div>What exactly is wanted when an attempt is made to instantiate an instance? Should it raise an error or return the previously created instance?</div><div><br></div><div>This attempt makes all calls to __new__ after the first return the same instance:</div>
<div><br></div><div><div>def singleton(cls):</div><div>    instance = None</div><div>    class sub(cls):</div><div>        def __new__(cls_, *args, **kwargs):</div><div>            nonlocal instance</div><div>            if instance is None:</div>
<div>                instance = super(sub, cls_).__new__(cls_, *args, **kwargs)</div><div>            return instance</div><div>    sub.__name__ == cls.__name__</div><div>    return sub</div><div><br></div><div>@singleton</div>
<div>class A(object):</div><div>    pass</div><div><br></div><div>print(A() is A())</div></div><div><br></div><div>Oscar</div><div><br></div></div>