Question

I'm still a beginner to python and i'm currently using version 2.7 for a little module i want to make.

It's for creating menus (for now, pretty simple)

UPDATE based on Daniel's and delnan's answers :

Each menu is an object :

class UiNavMenu(object):

    def __init__(self):
       self.title = title
       self.links = []

    def add(self, title, link, **kwargs):
        '''
        Add a link to the menu by creating a UiNavLink object.
        '''
        link = UiNavLink(title, link, kwargs)
        self.links.append(link)

    def clear(self):
        '''
        Clear all links in the menu
        '''
        self.links = []

    def __repr__(self):
        return "<UInavmenu object> Menu '%s' : %s links" % (self.title, len(self.links))

This is actually pretty basic.

And now the link object :

class UiNavLink(object):

    def __init__(self, title, link, **kwargs):

        self.title = title
        self.link = link

        for key, value in kwargs.items():
            self.key = value

So now, the thing i wanted to know is :

First, i know that python use a garbage collector and an object is destroyed at the and of his process.

But if i use the clean() method of a menu object like : menu.clean(), the menu will be destroyed with all of his contents. So the list in it (self.lists) will be destroyed too.

But does the links object (UiNavLink objects) contained in the list will be destroyed too so i don't have to take care of it ? or does i have to take care of it manually ?!

Thanks you very much :)

Yann

Was it helpful?

Solution

Python (or rather, the default CPython implementation) uses reference counting. When an object that contains a reference to another object - or contains a list that itself has a reference to an object - is deleted or goes out of scope, then the reference count of that object is decreased. When the reference count of an object gets to 0, it is garbage collected. So if your list is the only reference to those objects, they will be deleted when their holder is - but if other variables also hold references, they will not be.

A couple of points though. Firstly, you should very rarely be worrying about this. Python memory management is automatic, and memory leaks are quite hard to achieve (although not impossible).

Secondly, as delnan points out in the comment, __del__ is very definitely not the right way to go about it. __del__ is called automatically by Python (although it is not guaranteed to be called only once, or indeed at all), and the very fact that you have defined it is more likely to lead to memory leaks than if you had just left it undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top