On 18/02/24 11:35, Jonathan Gossage via Python-list wrote:
I am attempting to use the __new__ method in the following code:
class SingletonExample(object):

     _instance = None

     def __new__(cls, **kwargs):
         if cls._instance is None:
             cls._instance = super().__new__(cls, **kwargs)
         return cls._instance

     def __init__(self, **kwargs) -> None:
         our_attributes = ('h', 'x')
         if kwargs is not None:
             for k, v in kwargs.items():
                 if k in our_attributes:
                     setattr(self, k, v)

a = SingletonExample(h=1)

and I get the following result:

(PRV) jonathan@jfgdev:/PR$ python -m Library.Testing.test2
Traceback (most recent call last):
   File "<frozen runpy>", line 198, in _run_module_as_main
   File "<frozen runpy>", line 88, in _run_code
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 16, in
<module>
     a = SingletonExample(h=1)
         ^^^^^^^^^^^^^^^^^^^^^
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 6, in
__new__
     cls._instance = super().__new__(cls, **kwargs)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: object.__new__() takes exactly one argument (the type to
instantiate)

I am quite puzzled as it looks as if this code will not work if the
super-class is 'object'. Any suggestions on how to proceed?

Don't be puzzled. Read the error-message.

Change the super-call to: cls._instance = super().__new__(cls)
and happiness will follow...


That said, mystifications - not sure if this meets the/your definition* of "singleton", because:

- it can be aliased, eg
a = SingletonExample(h=1)
b = SingletonExample(x=2)

- when it is, the effect is an accumulation of attributes and values
a = SingletonExample(h=1)
b = SingletonExample(h=2)
print( a.__dict__, b.__dict__, )

- it can be re-created with a different value, eg
a = SingletonExample(h=1)
a = SingletonExample(h=2)

- and can be 'regenerated':
a = SingletonExample(h=1)
a = SingletonExample(x=2)

- all failures are silent


* noting "Nowadays, the Singleton pattern has become so popular that people may call something a singleton even if it solves just one of the listed problems." (https://refactoring.guru/design-patterns/singleton)


YMMV!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to