I found something curious about how python tracks objects in locals().
Considering the following script:
import gc
class T(object):
pass
def func1():
t = T()
#locals()
del t
#locals()
for o in gc.get_objects():
if type(o) is T:
print("STILL EXISTS")
func1()
Running with both locals() calls commented (as above) gives me no messages, indicated that the T() object created was garbage collected.
When I run it with the first locals() command (removing the first comment), it seems to create a dictionary that contains a reference to my t object. This dictionary is not associated to any names, so I wouldn't expect this dict to live as without being garbage collected.
The problem is that, running the code, I get "STILL EXISTS". Even if I delete t from the function namespace, the object is not garbage collected as the dict returned by locals() is still referring to it.
Funny enough, if I call locals() again (removing the second comment in the code above), then somehow the dictionary gets updated, it does not contain t in it and the object is garbage collected successfully (and I don't get an "STILL EXISTS" message).
I find this behaviour a bit weird.
Questions are:
- Is it normal that the dictionary returned by
locals()is long lived, even without associating it with any names? - Is it normal or is there any reason that this dictionary does not get updated automatically when deleting names from the current scope?
Edit: I am using cpython 3.6
Thanks!