Question About When Objects Are Destroyed (continued)
On 8/5/17 11:23 AM, Tim Daneliuk wrote:
> On 08/04/2017 07:00 PM, Chris Angelico wrote:
>> Again, don't stress about exactly when objects get
>> disposed of; it doesn't matter.
> Respectfully, I disagree strongly. Objects get build on the heap and
> persist even when they go out of scope until such time garbage
> collection takes place. This is unlike languages that build things in
> stack frames which naturally disappear with an exit of scope.
> For small or trivial programs, it does not matter. But when there is a
> lot of dynamic object construction - say, in very large programs, object
> factories, etc. - it can be important to harvest the space of expired
> objects sooner, rather than later. This, after all, is one of the
> rationale' for Python contexts - to ensure the release of resources no
> matter how the logic ends - correctly or by exception.
You might want to look into how CPython works more closely. It uses
reference counting, so most objects are reclaimed immediately when their
reference count goes to zero, such as at the end of local scopes. The
exception is objects that are in circular structures (A references B
which references C which references A, for example). Those have to wait
until an asynchronous garbage collection takes place.
You can run into problems if you accidentally are still referring to
large circular structures. Then it is important to understand where the
references are, and add some code to delete the references. But this is
unusual, and is not an issue with delayed garbage collection, but with
references keeping unwanted structures.
People in worlds with manually managed memory (such as C) are rightly
anxious about the details of their memory management. But they typically
don't need to bring that anxiety with them to Python.