Re: Python Tutorial Questions

Guido.van.Rossum@cwi.nl
Mon, 01 Aug 1994 21:08:20 +0200

> > >(1) Does Python have a garbage collector built in or do I have to
> > >manage my own memory with the del() operator?
> >
> > Python uses reference counts, so memory is managed for most objects.
> > You would need to use del() to break cycles.
>
> The del() instruction has me confused, and this "easy" answer simply
> supports my confusion. IF I have a "cycle", and the del() command can
> "break that cycle" by doing something as simple as:
>
> del(a)
>
> then it seems to me that the exact same "cycle" can be broken by
> doing:
>
> a = None
>
> I understand how reference counts work to achieve GC, and I don't see
> the justification for a del() command when the existing stuff (my
> example) works equally well. What am I missing?
>
> Note I *can* justify the presence of the del() on other grounds, but I
> *can't* for the life of me figure out why it comes up in GC
> discussion. (Except that it sounds like "free()" from C, or "delete
> ..." from C++).

Let me answer this, since I put "del" in the language.

It's true that for breaking a cycle you can use "a = None" instead of
"del a". I would still maintain that using "del" is cleaner if you're
not going to use a further on, but that's a matter of style -- I
understand that "a = None" corresponds more closely to the C/C++
idiom.

The true reason for having "del" is of course that sometimes you just
want to remove something from a namespace -- be it the global
namespace in an interactive session (if you're through with using an
object) or in the local namespace. A good example where you really
want to delete something from a namespace, and assigning None to
itjust isn't good enough, is when you use a temporary variable in the
initialization code of a module -- you don't want it to be exported to
other code that does "from <yourmodule> import *".

PS: del isn't a function, so using "del()" is redundant and even
confusing. Not that because of its semantics, it *can't* be a
function: "del a" deletes 'a' from the current namespace. A function
can't delete something from the calling namespace (except when written
by Steve Majewski :-).

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>