0

I was trying to write a Python object tracker using gc.get_objects() to be used inside an existing and rather complex IPython notebook in VS Code to track potential memory "leaks" or forgotten data sets. I wanted to be able to track when new objects are instantiated and when they are deleted/collected and hence disappear from gc.get_objects().

During this, I encountered a situation, which I cannot explain.

The condensed minimal example is as follows:

1st cell:

import gc

__objs = gc.get_objects()
_objs = [id(o) for o in __objs]

#del __objs

2nd cell:

variable = ["test"]

3rd cell:

id(variable) in _objs

Running these 3 cells either manually or using "run all" results in the last cell to evaluate to "False", as expected. But if the "del __objs" statement in the 1st cell is un-commented, then the last cell evaluates to "True", which does not make sense to me at all.

Running everything in one cell or inside a .py file results in the correct "False" evaluation.

What exactly is going on here? How can the id from a variable, that is instantiated in the second cell end up in _objs, but only if __objs is deleted? And why does this happen only wit 3 separate cells?

Any help would be highly appreciated!

3
  • How are you able to use in __objs after deleting __objs? It should have gotten an error saying the variable is not defined. Commented Nov 7, 2024 at 18:45
  • 2
    Basically, there were objects whose only reference lived in __objs. Delete the list, you delete those objects, and whatever ID number was associated with them is available to be used for ["test"]. Commented Nov 7, 2024 at 18:50
  • That the id is beeing reused makes total sense and answers my question. Thanks a lot !! Commented Nov 7, 2024 at 22:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.