{article Dive into Python}{title} {text} {/article}

>>> import fileinfo
>>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3")
>>> f.__class__
<class 'fileinfo.FileInfo'>
>>> f.__doc__
'store file metadata'
>>> f
{'name': '/music/_singles/kairo.mp3'}
>>>
>>>
>>>
>>> def leakmem():
f = fileinfo.FileInfo('/music/_singles/kairo.mp3')


>>> for i in range(100):
leakmem()

Every time the leakmem function is called, you are creating an instance of FileInfo and assigning it
to the variable f, which is a local variable within the function. Then the function ends without ever
freeing f, so you would expect a memory leak, but you would be wrong. When the function ends, the
local variable f goes out of scope. At this point, there are no longer any references to the newly created
instance of FileInfo (since you never assigned it to anything other than f), so Python destroys the instance for us.

No matter how many times you call the leakmem function, it will never leak memory, because every
time, Python will destroy the newly created FileInfo class before returning from leakmem.
The technical term for this form of garbage collection is "reference counting". Python keeps a list of references to
every instance created. In the above example, there was only one reference to the FileInfo instance: the local
variable f. When the function ends, the variable f goes out of scope, so the reference count drops to 0, and Python
destroys the instance automatically.