-2

Following is my code:

from ab import Ab

class Xyz:
    def __init__():
        self.a = Ab.get_unique_instance()

This is how the get_unique_instance() function is defined in ab.py

 class Ab:
     instance = []
     def get_unique_instance():
         if len(Ab.instance) == 0:
             new_instance = Ab() 
             Ab.instance.append(new_instance)
         return Ab.instance[0]

This is done to ensure only one instance of Ab is ever there. The problem is that the instance of Ab is still in memory even when the object created from class Xyz goes out of scope. How to delete this object explicitly?

Nilesh
  • 20,521
  • 16
  • 92
  • 148
web_ninja
  • 2,351
  • 3
  • 22
  • 43
  • If you only ever want one, why is `Ab.instance` a list? You could `weakref` the instance, so when everything else referencing it goes out of scope it is deleted. – jonrsharpe Jan 21 '15 at 11:52
  • You can do `del self.a` but, if you can provide how your are testing `instace of Ab is still in memory` then we can give better answer – Nilesh Jan 21 '15 at 11:52
  • You can also look at this [post](http://stackoverflow.com/q/6760685/1982962) for creating a singleton in python – Kobi K Jan 21 '15 at 11:53
  • I am running py.test and there are two instances of Xyz being created. The second instance of Xyz has all the data of the first instance and nothing gets updated for the second instance of Xyz. – web_ninja Jan 21 '15 at 11:55
  • **The second instance of Xyz has all the data of the instance of Ab created by first instance and nothing gets updated for the second instance of Xyz. – web_ninja Jan 21 '15 at 12:01

1 Answers1

2

Here is one possible implementation, using weakref to ensure that only the external references (i.e. not Single._instance) count towards the reference count:

import weakref

class Single(object):

    _instance = None

    def __init__(self):
        print "I've been born"

    def __del__(self):
        print "I'm dying"

    @classmethod
    def get_instance(cls):
        if cls._instance is not None and cls._instance() is not None:
            return cls._instance()
        instance = cls()
        cls._instance = weakref.ref(instance)
        return instance

Therefore you have at most one Single at a time, but can have none if all references are removed (and a new one will be created on the next call to the class method). In use:

>>> a = Single.get_instance()
I've been born
>>> b = Single.get_instance()
>>> a is b
True
>>> del a
>>> del b
I'm dying
>>> c = Single.get_instance()
I've been born
>>> del c
I'm dying
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437