I tried to understand how a particular single element decorator implementation for a class works, but I just got confused.
Here is the code:
def singleton(cls): instance = None @functools.wraps(cls) def inner(*args, **kwargs): nonlocal instance if instance is None: instance = cls(*args, **kwargs) return instance return inner
@deco is the syntax sugar for cls = deco(cls) , so in this code, when we define our cls class and wrap it with this singleton decorator, cls will no longer be a class, but a function. Python dynamically searches for which objects the variables belong to, so later we try to create an instance of our class, and this line of code works instance = cls(*args, **kwargs) , will we move on to infinite recursion? cls not a class at the moment, it is a function, so it should call itself by going into recursion.
But it works great. A singleton is created, and recursion does not occur. How it works?
python decorator singleton
A. Churshin
source share