Home > Back-end >  Local varible of function stays in memory. Why gc doesn't cleaning it?
Local varible of function stays in memory. Why gc doesn't cleaning it?

Time:01-29

I'm wondering why this code returns same id of a variable. Doesn't interpreter suppose to clean a from memory after f() finished? Is this behavior result of some CPython optimization? Can we force it to clean a object? gc.collect() doesn't help in this. I thought that waiting for some time may change this behavior, but it doesn't.

import time

def f():
    a = "wat wat wat wat wat wat wat wat"
    print(id(a))

f()

for i in range(30):
    time.sleep(1)
    s = "/" if i % 2 == 0 else "\\"
    print(s, end="", flush=True)

print()
f()
# Tested with python 3.10.8
# 140443262854256
# /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
# 140443262854256

CodePudding user response:

This is due to a feature called string interning. When several string variables have the same value, Python only stores one copy of the string in memory. This optimization saves memory and allows string comparison to be performed faster. Note that this is a language-specific feature, and does not apply to programming languages in general. Also, string interning does not always happen, read more here.

CodePudding user response:

GC in python does reference counting and deletes the objects automatically when no references to object left.

In your example, you still have the f function in your code at the end, keeping all the references to function f and everything in it alive.

To be able to assist GC, you can always delete the objects using del.

del f

CodePudding user response:

id returning the same value twice has nothing to do with a variable outliving its scope. Two objects whose lifetimes do not overlap can have the same id, as the id of the first is available to reuse for the second. Consider

>>> id([]) == id([])
True

[] always produces a new list object (as lists are immutable, you can't intern them). But this produces true because the list passed to the first call to id is reclaimed before the second call to id is made, meaning the second list can have the same id as the first.

  • Related