Alexey Muranov <[email protected]> added the comment:
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.
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue36827>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com