Explain how does Python memory management work?

Technology CommunityCategory: PythonExplain how does Python memory management work?
VietMX Staff asked 3 years ago

Python — like C#, Java and many other languages — uses garbage collection rather than manual memory management. You just freely create objects and the language’s memory manager periodically (or when you specifically direct it to) looks for any objects that are no longer referenced by your program.

If you want to hold on to an object, just hold a reference to it. If you want the object to be freed (eventually) remove any references to it.

def foo(names):
  for name in names:
    print name

foo(["Eric", "Ernie", "Bert"])
foo(["Guthtrie", "Eddie", "Al"])

Each of these calls to foo creates a Python list object initialized with three values. For the duration of the foo call they are referenced by the variable names, but as soon as that function exits no variable is holding a reference to them and they are fair game for the garbage collector to delete.