3 ms·
This reads very obviously AI-generated to me. Aside from that, the Singleton design pattern was recognized as overused and fraught with issues a long time ago,
by zahlman 2y ago
This reads very obviously AI-generated to me. Aside from that, the Singleton design pattern was recognized as overused and fraught with issues a long time ago, and is usually the sort of thing that gets produced by people who believe that reading books like the Group of Four book actually teaches one how to program.
Python is a highly dynamic language and there are any number of ways to circumvent this prevention deliberately. (Python is so dynamic that it's not even clear whether "are these two objects instances of the same class?" is a well-defined question; you can answer this in terms of `isinstance`, but you might not like the answer if e.g. you defeat the caching mechanism in order to import two copies of a module, or if you modify the `__class__` of an object, or...)
As for avoiding mistakes, such a Singleton pattern simply isn't Pythonic - it's far easier to just create one instance and pass it around (you never accidentally create an extra instance if you never think of calling the constructor aside from at a clear entry point). Failing that, one can have instances share state (rather, have no state of their own, and use the state of the class itself - sometimes elaborated as a "borg" or "monostate" pattern: https://stackoverflow.com/questions/1318406 https://stackoverflow.com/questions/1318406).
Aside from that, it's often unclear whether one actually "wants a singleton" in the first place, and what semantics are really desirable. Sometimes it turns out you really want a per-thread instance, or a per-subclass instance, or....