Embedding Python: estimate size of dict/list

Chris Angelico rosuav at gmail.com
Mon Mar 28 19:18:10 EDT 2011


Hi! New to the list, apologies if I'm in breach of protocol.

I have an application that embeds Python to allow third-party
scripting. The Python code returns data to the application in the form
of a list or dictionary, and I'd like to have a quick check on the
size of the outputted object before my code goes too deep into
processing it.

Obviously I could use PyObject_Str() and PyString_Size() to get a
decent figure, but that seems like overkill.

What I'm hoping for is some simple function that zips through a
complex object and sums its approximate memory usage. Is there one?

It doesn't have to be 100% precise; I just want to distinguish between
the normal (under a KB, or maybe a couple KB at most) and the
ridiculous (megs and megs of junk that I'd have to process and send
over the network only for it to be discarded at the other end). If
there's some sort of "if this ran out of references now, how much
memory would be freed" function, that would be awesome.

My code is in C++, is embedding Python 2.6.6, and is running on Ubuntu
Linux. If the solution is to move to Python 3.x then this may be an
option.

Hoping there's something around!

Chris Angelico
aka Rosuav



More information about the Python-list mailing list