[Tutor] How python keeps track of objects

Steven D'Aprano steve at pearwood.info
Sun Nov 23 10:47:58 CET 2014

On Sat, Nov 22, 2014 at 09:28:35PM -0500, Mitch Raful wrote:
> If I have code similar to this:
> for object in objects:
>     do_something(object)
> def do_something(obj):
>      other_object = Class( obj.property)
>      other_object.method( arg1, arg2)
>     do_stuff here with other_object
>     if problem:
>          print( obj.property )
> My concern is that the for loop will wreak havoc with objects created in
> the function do_something.

What sort of havoc are you thinking of?

> Do I need to use Threading for the
> do_something?  Or does the interpreter keep track of all the
> 'other_object's as the for loop calls the function?

I'm not really sure what your concern is, so please forgive me if I 
don't quite answer it.

The way Python works is that every time an object is created, the 
interpreter's garbage collector tracks whether it is accessible from 
anything. The way it does this depends on the version of Python being 
used, e.g. CPython uses reference counting, Jython uses the Java garbage 
collector, IronPython uses the .Net garbage collector, etc. As Python 
programmers, we don't have to care about the difference between garbage 
collectors, we just trust that they do their job.

Once the object is no longer accessible from anything, the garbage 
collector automatically deletes the object. But until then, you can 
trust that the interpreter will hold onto any object that you might use.

You don't need threading for normal Python programs. The only time you 
need bother about threading is if you want to run two separate parts of 
your code simultaneously. Threading creates a whole range of challenges 
for the programmer, in general you should not use it unless you really 
need it. (Fixing threading race conditions, deadlocks and assorted other 
bugs is *much* harder than debugging unthreaded code.)


More information about the Tutor mailing list