1

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?

Community
  • 1
  • 1
Randy
  • 908
  • 12
  • 30
  • When `a` is detached from `Repository.all_repos`, it behaves like any other object, so it *may be* garbage collected when the last reference to it disappears. It doesn't need to be, though. – Fred Foo Nov 27 '13 at 21:19
  • http://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works – Alberto Megía Nov 27 '13 at 21:20

1 Answers1

1

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

rdodev
  • 3,164
  • 3
  • 26
  • 34