Why does the first loop go wrong with Python3

Chris Angelico rosuav at gmail.com
Tue May 19 13:11:50 EDT 2015


On Wed, May 20, 2015 at 2:39 AM, Cecil Westerhof <Cecil at decebal.nl> wrote:
> By the way, what also works is:
>     p = None
>
> But it was just a try in ipython3. I would never do this in real code.
> I was just curious if this would be handled correctly and it is. :-)

That _may_ work, but it depends on their not being any other
references to it, and also depends on it being garbage-collected
promptly. Neither is guaranteed. Explicitly wait()ing on it is a
guarantee.

Simply dropping the object is a good way to "probably dispose" of
something that you don't care about. For instance, you asynchronously
invoke VLC to play some audio alert, and the subprocess might finish
before you're done with the current function, or might finish after.
You don't really care about its actual termination, and certainly
don't want to delay anything waiting for it, but you do want to clean
up resources at some point. Dropping the object (keeping no references
to it, returning from the function you called it from, unsetting any
references you have, whatever makes sense) will normally mean that it
gets garbage collected and cleaned up _at some point_, without really
guaranteeing exactly when; for instance, if you have an alert like
this once per hour and watch 'top' for the number of zombies, you'll
probably see some now and then, but they'll never get to apocalyptic
numbers.

ChrisA



More information about the Python-list mailing list