Python memory management

Posted in hmmm , python

Reference Counting

Python memory management is done by reference counting. When the number of references of an object reaches zero, it gets deleted.

This is good because it’s fast and easy to handle. If you make an object a global object and modify it locally, the global will continue to exist and stay accessible outside of the local function.

How it works under the hood is determined by which Python interpreter you’re using.

Deterministic Destruction

The del method is called for you automatically just before an object is destroyed, so it’s also useless to call it yourself. And unlike C++, python’s delete method does not actually call the destructor.

“When” an object is actually deleted is determined by which Python interpreter you’re using. And when it does actually get deleted does the memory get freed into a shared pool or is it released into the wild? Calling __del__ only removes access to the object from the local or global namespace. It does not mean the memory location has been freed.

Starting simple…

Everything is a reference to an object.

>>> type(”hello”)

Just like anything else, it lives somewhere in memory.

>>> id(’hello’)
3077235392L

And since’s its a string, you can invoke any string method.

>>> ‘rootninja’.islower()
True
>>> ‘rootninja’.capitalize()
‘Rootninja’
>>> ‘rootninja’.lstrip(’root’)
‘ninja’

If you assign a string to a variable, you will find the memory locations are the same because you’re not creating a copy, you’re just pointing to the same address.

>>> x = ‘rootninja’
>>> id(x)
3077221888L
>>> id(’rootninja’)
3077221888L

When you lose access to an object, that memory is freed on its own. Assign something else to x.

>>> x = ‘Rygar’
>>> id(x)
3077235200L
>>> id(’Rygar)
3077235200L

Now look at the old string’s address again.

But the location of that string also changed.

>>>id(’rootninja’)
3077221984L

Was the original string destroyed as soon as x changed? or did it hang around until you attempted to access it again?

It gets more complicated when you try to mix Python with C.
http://docs.python.org/c-api/memory.html

Posted by admica   @   19 May 2010

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
« Stack Smashing Detected by parted trying to write to read-only device
Next Post
Google’s playable Pacman videogame without Flash »
Powered by Wordpress   |   Lunated designed by ZenVerse