Skip to content
Snippets Groups Projects

Python 3 Singleton

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Mikaël Guichard
    Edited
    Singleton.py 590 B
    def singleton(cls):
        instance = None
    
        def ctor(*args, **kwargs):
            nonlocal instance
            if not instance:
                instance = cls(*args, **kwargs)
            return instance
    
        return ctor
    
    
    @singleton
    class Bar:
        def __init__(self, val):
            self.val = val
    
    # ----------------------------------------------------
    
    a = Bar("var1") # Le paramètre var1 est enregistré lors de la création de l'instance
    b = Bar("var2") # Récupération de l'instance déjà créée. Le paramètre ne sera donc pas enregistré
    
    print(a.val, id(a))
    print(b.val, id(b))
    print(a is b)
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment