reference counting for garbage collection

Gareth McCaughan Gareth.McCaughan at pobox.com
Mon Dec 10 16:30:18 EST 2001


Paul Brian wrote:

> If I create a function :
> 
> def foo(server):
>     ''' creates a connection to server and returns it'''
>     conn = mycleverconnection(server)
>     return conn
> 
> and then I do
> 
> x = foo('10.x.x.x.')
> 
> will the function foo still keep some reference to conn such that
> 
> del(x)
> 
> will *not* destroy conn but conn will still stay alive?

No, it won't.

> if not
> 
> 1) is there some tool that shows me what exactly is alive in the python
> environment

No.

> 2) is there some notes on references, keep alives and other mysterious
> things in the docs

The "Extending and embedding Python" docs describe the
mysterious things you need to understand if you're, erm,
embedding or extending Python. If you aren't doing that,
then there isn't really anything very complicated. Objects
go away when nothing refers to them any more. When an
object is referenced, but only "circularly" (i.e., there's
no way of getting at it from any live scope) it may
go away, but not necessarily immediately.

It's arguably bad style to rely on objects going away as
soon as they're no longer referenced, because if Python
switches over completely to a "real" GC some time in the
future then it will stop being true.

> 3) what have I done wrong in the stuff I just wrote (no not the above:-)?
> 
> (Ok so 3 is my problem :-)

That's a pity, since you haven't told us anything about
the stuff you just wrote except that it isn't what you
put in the article :-). That makes it hard to work out
what might be wrong.

Are you getting things disappearing when you don't expect
them to, or things not disappearing when you do expect them to,
or something else?

If something isn't disappearing when you expect, that might
be because it's part of a circular chain of references.

    def make_cycle():
        a = [0]
        b = [a]
        a[0] = b

If you call make_cycle() then the list named "a" doesn't
disappear when a goes out of scope (because the list named
"b" refers to it), and the list named "b" doesn't disappear
when b goes out of scope (because the list named "a"
refers to it). Recent versions of Python are equipped
with a garbage collector that will pick those up, but
it won't necessarily do so as soon as make_cycle() returns.
It's possible to compile Python without the GC, too.

If something is disappearing when you don't expect it to,
that's odder. You probably have a bug either in your code
or in Python or in your brain. You haven't given enough
information to tell which. :-)

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc



More information about the Python-list mailing list