non-owning references?

Ben Finney ben+python at benfinney.id.au
Fri Jul 24 09:06:34 EDT 2009


Utpal Sarkar <doetoe at gmail.com> writes:

> Is there a way I can tell a variable that the object it is pointing
> too is not owned by it, in the sense that if it is the only reference
> to the object it can be garbage collected?

Python doesn't have “pointers”, and doesn't really have “variables”
either, at least not how many other languages use that term.

What it does have is references to objects
<URL:http://effbot.org/zone/python-objects.htm>.

> on first instantiation the object is created and a reference is kept
> in the class, that is used to return the same object in subsequent
> instantiations. When all instances go out of scope, the reference in
> the class is still there, preventing it from being garbage collected,
> but since the instance can be huge, I would like it to be.

What you are asking for is called a “weak reference” and is provided
by the ‘weakref’ module <URL:http://docs.python.org/library/weakref>.

-- 
 \      “Patience, n. A minor form of despair, disguised as a virtue.” |
  `\                   —Ambrose Bierce, _The Devil's Dictionary_, 1906 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list