mardi 26 juin 2018

Singleton Implementation using Function

I read about multiple approaches of creating a singleton function in this SO question.

I came up with another approach

def my_singleton():

    if not my_singleton.instance:
        class MyClass:
            pass

        my_singleton.instance = MyClass()

    return my_singleton.instance

What is wrong with this approach compared to other approaches mentioned in previous SO question? Is there any implication related to memory/GC/thread safety/lifecycle of instance. I am asking this because other approaches looks quite complicated for a beginner (metaclass, decorators, baseclass, decorators returning class)

Aucun commentaire:

Enregistrer un commentaire