A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2004-March/043682.html below:

[Python-Dev] PEP 318: Singleton decorator

[Python-Dev] PEP 318: Singleton decorator [Python-Dev] PEP 318: Singleton decoratorKa-Ping Yee python-dev at zesty.ca
Tue Mar 30 06:17:08 EST 2004
Hi folks.

Earlier messages suggested a nice singleton decorator, which is shown
in the draft PEP:

    def singleton(cls):
        return cls()

    class MyClass [singleton]:
        ...

This has been mentioned as an argument against requiring or recommending
that decorators accept and return callables.

But i don't think this is a good way to write a singleton, because then
the user of the class has to get instances by saying "MyClass" instead
of "MyClass()".  Better would be:

    def singleton(cls):
        instances = {}
        def getinstance():
            if cls not in instances:
                instances[cls] = cls()
            return instances[cls]
        return getinstance

Then, code that gets an instance makes more sense.  MyClass() still
instantiates MyClass -- it just always returns the same instance.

I respectfully suggest that the PEP use the latter implementation in
its singleton example instead.


-- ?!ng

More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4