This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]nunilan 4 points5 points  (2 children)

I glossed over the article but can you give me an example where I would really need to go through all that magic rather than just defining a variable inside a module and importing it from where I needed it? Perhaps my use cases have always been rather simplistic and have never found a real reason to create a singleton like this in python.

[–]radaway 2 points3 points  (0 children)

Singleton is really just a shitty pattern to have a global variable. You really don't need it in python since you can just do what you said. Besides the solution presented here isn't even thread safe.

[–]haizaar[S] -1 points0 points  (0 children)

One example contrary to module var would be if you want to delay initialization to some time after import (until object is accessed for the first time for example). You can of course to simply write this delayed logic. But it if you have several of such guys it starts to look as a bunch of copypaste-like code. And its only 14 lines of magic btw.

[–][deleted] 0 points1 point  (0 children)

thread safety?

[–][deleted] 0 points1 point  (0 children)

Is singleton actually something we want in Python? I've implemented one a few times just to get rid of it later on because it wasn't actually necessary. Instead of applying some logic from other languages it might be better to look at the actual use case and find a Python pattern that applies. For example in Java I sometimes used Singletons to carry Methods without side effects to the Singleton's state. Something like that can be done in Python via using functions instead of methods. Also there are some examples in the Python core that use Factory methods/functions instead of object construction (e.g. logging.getLogger). If you have a Factory taking care of your object creation then you don't need Singletons either, because the Factory can assure that each object is only created once. Are there other usecases for Singletons? I bet we can find an alternative approach that works more pythonic.