This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author alexey-muranov
Recipients SilentGhost, alexey-muranov, rhettinger
Date 2019-05-11.12:37:58
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1557578279.21.0.328035707226.issue36827@roundup.psfhosted.org>
In-reply-to
Content
I see that I am not the only one who got bitten by this unexpected behaviour (though the others might have not realised it).  There is a question ["Creating a singleton in Python"][1] on StackOverflow which was posted in 2011 and by now has the total of 737 upvotes.  Here is a code snippet from the question:

    class Singleton(object):
        _instance = None
        def __new__(class_, *args, **kwargs):
            if not isinstance(class_._instance, class_):
                class_._instance = object.__new__(class_, *args, **kwargs)
            return class_._instance

    class MyClass(Singleton, BaseClass):
        pass

[1]: https://stackoverflow.com/q/6760685

Currently this does not work as expected, try:

    class Failed(Singleton):
        def __init__(self, _):
            pass

    Failed(42)  # TypeError: object.__new__() takes exactly one argument ...

There is a similar code snippet in the accepted [answer][2] with 507 upvotes:

    class Singleton(object):
        _instances = {}
        def __new__(class_, *args, **kwargs):
            if class_ not in class_._instances:
                class_._instances[class_] = super(Singleton, class_).__new__(
                    class_, *args, **kwargs
                )
            return class_._instances[class_]

    class MyClass(Singleton):
        pass

[2]: https://stackoverflow.com/a/6798042

This does not work either, for the same reason.
History
Date User Action Args
2019-05-11 12:37:59alexey-muranovsetrecipients: + alexey-muranov, rhettinger, SilentGhost
2019-05-11 12:37:59alexey-muranovsetmessageid: <1557578279.21.0.328035707226.issue36827@roundup.psfhosted.org>
2019-05-11 12:37:59alexey-muranovlinkissue36827 messages
2019-05-11 12:37:58alexey-muranovcreate