How to always use the same instance of a class in Python?
Question: I am using the following solution to maintain a list of classes instances:
<http://stackoverflow.com/a/12102163>

Now I want to use that list to make sure that there is always only one
instance of the class. Renewed initializations of the class should return the
one existing instance.

The code I have is:

    
    
    class MyClass:
    
        instances = []
    
        def __init__(self):
            if not MyClass.instances:
                self.data=1234
            else:
                self = MyClass.instances[0]
    

So:

    
    
    >> a=MyClass()
    >> a.data
    1234
    

And b=MyClass() should return the same instance as a. This is not working.
What is wrong with my code?

**EDIT: OK, so it turns out I am looking for the singleton pattern, but
couldn't recreate it myself. Can anyone please explain why my code does not
work?**


Answer: Going on your code line and your style. You can make following modifications:-

    
    
    class MyClass:
        instance = None
        def __init__(self):
            self.data=1234
            MyClass.instance = self
    
    def get_myclass():
        if MyClass.instance:
            return MyClass.instance
        return MyClass()
    

`get_myclass` would be a wrapper function for creating class objects. Trying
the code.

    
    
    >>> import instance
    >>> a=instance.get_myclass()
    >>> b=instance.get_myclass()
    >>> a is b
    True
    

