Message342185
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. |
|
| Date |
User |
Action |
Args |
| 2019-05-11 12:37:59 | alexey-muranov | set | recipients:
+ alexey-muranov, rhettinger, SilentGhost |
| 2019-05-11 12:37:59 | alexey-muranov | set | messageid: <1557578279.21.0.328035707226.issue36827@roundup.psfhosted.org> |
| 2019-05-11 12:37:59 | alexey-muranov | link | issue36827 messages |
| 2019-05-11 12:37:58 | alexey-muranov | create | |
|