MediumConcept

How does Python manage memory and garbage collection?

Technology:
Python
Experience:
Mid-level,
Senior

Quick answer

CPython frees objects mainly through reference counting, deleting an object as soon as nothing refers to it, and uses a cyclic garbage collector to clean up groups of objects that reference each other.

Detailed explanation

Every object keeps a count of references to it. When the count reaches zero its memory is released immediately. This makes cleanup predictable, but reference counting cannot free cycles, such as two objects that point at each other. The gc module's generational collector periodically finds and frees those.

Memory leaks in Python are usually objects kept alive by long-lived references: global lists or dictionaries, caches without limits, or closures. Use weakref for caches that should not keep objects alive, __slots__ to shrink many small objects, generators to stream data, and tools such as tracemalloc to see what is allocating memory.

  • PythonMedium

    What are generators and the yield keyword in Python?

    A generator is a function that uses yield to produce values one at a time and remembers its state between calls, so it can process large or infinite sequences without holding everything in memory.

    Mid-level 路 Senior 路 Functions & Scope
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    Why should you not use a mutable default argument in Python?

    Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    What is the difference between @staticmethod and @classmethod in Python?

    A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.

    Junior 路 Mid-level 路 Object-Oriented Programming
  • PythonMedium

    What are decorators in Python and how do they work?

    A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.

    Mid-level 路 Senior 路 Functions & Scope