Search code examples
pythonooppython-collections

How/When does Python garbage collect objects which contain a collection of all of their own type?


I am working on a Python class that is structured like the example in this answer: https://stackoverflow.com/a/1383744/576333. The class itself is keeping track of all created objects using a dictionary.

class Repository(object):

    # All repositories are stored in this class-level dictionary such that 
    # all instances of this class maintain the same set.
    all_repos = {}   

    def __init__(self, name, data):
        """
        Create a repository object. If it has the required tags, include it in
        the collection of all repositories.
        """

        # Don't add it if it already exists
        if not name in Repository.all_repos:

            # Store the attributes
            self.__dict__ = data
            self.__dict__['name'] = name

            Repository.all_repos.update({ name: self })

My question is what happens in python when I create a delete/remove method and want to purge an instance of Repository from the all_repos dictionary? Here is what I was planning on doing a method like that:

def remove(self):
    repo = Repository.all_repos.pop(self.name) # pop it out
    print "You just removed %s" % repo.name

With the following usage:

a= Repository('repo_name', {'attr1':'attr1_value',...}
a.remove()

At this point, a still exists, but not in Repository.all_repos. When will Python finally remove a?


Solution

  • I found this article to be very helpful to visualize garbage collection. It uses Ruby's GC for comparison, but it is well worth the read:

    http://patshaughnessy.net/2013/10/24/visualizing-garbage-collection-in-ruby-and-python