Java singletonMap in Python

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Sep 23 19:50:11 EDT 2012


On 24 September 2012 00:14, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:

> 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.
>

What exactly is wanted when an attempt is made to instantiate an instance?
Should it raise an error or return the previously created instance?

This attempt makes all calls to __new__ after the first return the same
instance:

def singleton(cls):
    instance = None
    class sub(cls):
        def __new__(cls_, *args, **kwargs):
            nonlocal instance
            if instance is None:
                instance = super(sub, cls_).__new__(cls_, *args, **kwargs)
            return instance
    sub.__name__ == cls.__name__
    return sub

@singleton
class A(object):
    pass

print(A() is A())

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120924/2b6260e4/attachment.html>


More information about the Python-list mailing list