Hooking into Python's memory management

Gregory Ewing greg.ewing at canterbury.ac.nz
Wed May 4 23:16:45 EDT 2011


Daniel Neilson wrote:

>  1) Maintain a list of object id()'s for objects that have been created. 
> Ideally, this list would also contain the file & line number where the 
> object was created.

>  2) Provide a "deallocate" function that will remove a given object's 
> id() from the list from (1).

>  3) Print out an error message if the python script terminates with a 
> non-empty list from (1). Preferably with a list of objects that are 
> still "allocated."

I don't think this will work out quite the way you seem to be
imagining. Consider that Python creates a lot of objects behind
the scenes without you doing anything specific to "allocate"
them. Examples include the dicts holding module and class
namespaces, all the strings representing names in loaded code,
ints, floats and strings representing literals in the code,
etc.

If you automatically add any object of any of these types
to the "allocated" list, these implicitly-created objects will
all still be present in it when the program terminates, and
the student will be told off for failing to deallocate them.

An alternative might be to provide an allocate() function which
the student is expected to use on any explicitly-created object.
But there wouldn't be any way of enforcing this.

Personally I think the whole idea is misguided, and it would be
better to teach these concepts in the context of a language
where they actually matter, which these days more or less
means C. If teaching C in the first year in parallel with
Python is considered too steep, then leave explicit memory
management until later in the curriculum.

(It's really a shame that Pascal is not taught any more. It
provided a fairly clean environment for teaching about things
like this, without getting so close to the machine that you
get your nosed rubbed in segfaults.)

-- 
Greg



More information about the Python-list mailing list