Youโ€™re the Expert!

pynfinity

Build mountain with each pebble ๐Ÿง—

Topics | Stepping Stones
Official Guides
Community Contributions
๐Ÿ“–
Guides
In-depth topic walkthroughs with examples
19 topics
โšก
Bytes
Detailed notes, tutorials & code deep-dives
83 posts
๐Ÿ’Ž
Bits
Quick code snippets โ€” read in one scroll
42 snippets
๐Ÿ“–

Official Guides

โšก

Bytes โ€” Tutorials & Deep-Dives

๐Ÿงฉ
๐Ÿงฉ Regular Expressions
Regular expressions are a powerful tool for various kinds of string manipulation.
pynfinity 2027-06-23
โณ
โณ Time Series Resampling
Resampling allows you to change the frequency of your time series data, e.g., from daily to monthly.
santoshtvk 2028-01-09
๐ŸŽ›๏ธ
๐ŸŽ›๏ธ Multiprocessing
Multiprocessing allows you to create processes, which can run in parallel on multiple CPU cores.
pynfinity 2025-01-23
๐Ÿณ
๐Ÿณ Dockerfiles
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.
pynfinity 2023-10-31
๐Ÿ“ธ
๐Ÿ“ธ OpenCV Image Reading
OpenCV is a huge open-source library for computer vision, machine learning, and image processing.
pynfinity 2025-05-02
โณ
โณ Time Series Resampling
Resampling allows you to change the frequency of your time series data, e.g., from daily to monthly.
santoshtvk 2026-01-01
๐Ÿ“„
๐Ÿ“„ JSON Handling
JSON is a lightweight data interchange format inspired by JavaScript object literal syntax.
pynfinity 2024-09-15
โšก
โšก Python async/await โ€” Asynchronous Programming Guide
asyncio enables concurrent I/O-bound tasks in Python without threads. Learn async/await to write high-performance APIs and web scrapers.
santoshtvk 2025-12-02
โ™พ๏ธ
โ™พ๏ธ Python Generators โ€” Memory-Efficient Iterators
Generators produce values on demand instead of storing everything in memory. Perfect for large datasets, streaming, and infinite sequences.
santoshtvk 2026-09-01
๐Ÿ”
๐Ÿ” Python Environment Variables โ€” Managing Config Safely
Never hardcode secrets in Python code. Environment variables and .env files keep API keys, passwords, and configs out of source code.
santoshtvk 2026-05-15
๐Ÿ“š
๐Ÿ“š Collections Module
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers.
pynfinity 2023-04-17
๐Ÿšช
๐Ÿšช Context Managers
Context managers allow you to allocate and release resources precisely when you want to.
pynfinity 2023-05-13
โšก
โšก FastAPI Endpoints
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.
pynfinity 2023-12-24
๐Ÿผ
๐Ÿผ Pandas DataFrames
Pandas DataFrame is a primary two-dimensional tabular data structure in the pandas Python library. They allow you to store and manipulate tabular data efficiently.
santoshtvk 2025-07-01
๐Ÿท๏ธ
๐Ÿท๏ธ Type Hinting
Type hinting helps you document your code and catch errors early.
santoshtvk 2028-01-29
โœ๏ธ
โœ๏ธ Python f-Strings โ€” The Modern Way to Format Strings
f-strings (formatted string literals) are the fastest, most readable way to format strings in Python 3.6+. Master them completely.
santoshtvk 2026-07-14
๐Ÿ“ฆ
๐Ÿ“ฆ Dataclasses
Dataclasses provide a decorator and functions for automatically adding generated special methods to classes.
pynfinity 2023-08-19
๐Ÿ–ฅ๏ธ
๐Ÿ–ฅ๏ธ Python argparse โ€” Building Command-Line Tools
argparse turns Python scripts into professional CLI tools with automatic help messages, type validation, and optional/required arguments.
santoshtvk 2025-11-21
๐Ÿ“Š
๐Ÿ“Š Python dataclasses โ€” Clean Data Models in Python
The @dataclass decorator auto-generates boilerplate code for data-holding classes โ€” __init__, __repr__, __eq__ all for free.
santoshtvk 2026-02-06
๐Ÿ“ง
๐Ÿ“ง How to Send Email with Python
Python makes sending emails straightforward using the smtplib module. Learn to send plain text, HTML emails, and attachments.
santoshtvk 2024-06-12
๐Ÿ–ฅ๏ธ
๐Ÿ–ฅ๏ธ OS Module
The os module provides a portable way of using operating system dependent functionality.
santoshtvk 2025-05-27
๐Ÿ“‚
๐Ÿ“‚ How to Read a CSV File in Python
Reading CSV files is one of the most common tasks in Python. The built-in csv module and pandas both make it simple.
santoshtvk 2024-05-23
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ NetworkX Graphs
NetworkX is a Python package for the creation, manipulation, and study of the structure of complex networks.
pynfinity 2025-03-06
๐Ÿ•ท๏ธ
๐Ÿ•ท๏ธ Python Web Scraping with Selenium โ€” Dynamic Sites
Selenium controls a real browser for scraping JavaScript-heavy sites that BeautifulSoup can't handle. Automate login, fill forms, click buttons.
santoshtvk 2027-05-16
โœจ
โœจ Jupyter Magic Commands
Magic commands are special commands that you can run in Jupyter notebooks to perform special tasks.
santoshtvk 2024-10-17
๐Ÿ“Š
๐Ÿ“Š Interactive Plots with Plotly
Plotly allows you to create interactive charts that you can zoom, pan, and hover over.
santoshtvk 2024-07-23
๐ŸŒฒ
๐ŸŒฒ Git Basics
Git is a distributed version control system for tracking changes in source code during software development.
pynfinity 2024-04-16
๐ŸŽ€
๐ŸŽ€ Decorators
Decorators allow you to modify the behavior of a function or class.
pynfinity 2023-09-24
๐Ÿ“
๐Ÿ“ Python File Handling โ€” Read, Write, and Append Files
Python file handling covers reading, writing, and appending data. The 'with' statement ensures files are always closed properly.
santoshtvk 2026-08-08
๐Ÿ”
๐Ÿ” Python Type Hints โ€” Write Safer, Self-Documenting Code
Type hints make Python code more readable, catch bugs earlier, and supercharge IDE autocomplete. Introduced in Python 3.5, improved in every version since.
santoshtvk 2027-05-05
๐Ÿชต
๐Ÿชต Logging
Logging is a means of tracking events that happen when some software runs.
santoshtvk 2024-12-03
โ˜๏ธ
โ˜๏ธ AWS S3 with Boto3
Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python.
santoshtvk 2023-03-18
๐Ÿ”ฅ
๐Ÿ”ฅ Seaborn Heatmaps
Seaborn makes it easy to create attractive heatmaps to visualize correlation matrices or 2D data.
santoshtvk 2027-08-28
โณ
โณ AsyncIO
AsyncIO is a library to write concurrent code using the async/await syntax.
santoshtvk 2023-02-23
โž—
โž— Math Module
This module provides access to the mathematical functions defined by the C standard.
pynfinity 2024-12-18
๐Ÿ“–
๐Ÿ“– Python Dictionary Methods โ€” Complete Guide
Python dictionaries are flexible key-value stores. Mastering dict methods unlocks faster, more readable data manipulation code.
santoshtvk 2026-04-15
๐Ÿ“ฆ
๐Ÿ“ฆ Virtual Environments
Virtual environments allow you to manage dependencies for different projects separately.
santoshtvk 2028-02-11
โšก
โšก Generators
Generators are a simple way of creating iterators. They use the `yield` statement.
pynfinity 2024-03-14
๐Ÿงต
๐Ÿงต Multithreading
Threading allows you to run multiple operations concurrently in a single process.
pynfinity 2025-02-09
๐Ÿ“‰
๐Ÿ“‰ Statsmodels OLS
Statsmodels allows you to explore data, estimate statistical models, and perform statistical tests.
santoshtvk 2027-10-18
โš™๏ธ
โš™๏ธ Sys Module
The sys module provides access to some variables used or maintained by the interpreter.
santoshtvk 2027-11-21
๐Ÿ—บ๏ธ
๐Ÿ—บ๏ธ Folium Maps
Folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js library.
pynfinity 2024-01-31
๐Ÿงน
๐Ÿงน Data Cleaning with Dropna
Missing data is a common problem. Pandas provides `dropna()` to easily remove rows or columns with null values.
santoshtvk 2026-01-01
๐Ÿ›ก๏ธ
๐Ÿ›ก๏ธ Pydantic Models
Pydantic performs data validation and settings management using Python type annotations.
pynfinity 2025-09-10
๐ŸŽ
๐ŸŽ Python Decorators Explained with Examples
Decorators are one of Python's most elegant features. They wrap functions to add extra behaviour โ€” without changing the original function code.
santoshtvk 2026-03-19
๐Ÿงช
๐Ÿงช Python Testing with unittest and pytest
Testing your Python code prevents bugs from reaching production. pytest makes writing and running tests fast, readable, and enjoyable.
santoshtvk 2027-04-01
๐Ÿค–
๐Ÿค– Scikit-Learn Linear Regression
Linear Regression is the 'Hello World' of Machine Learning. Scikit-Learn makes it a breeze to implement.
pynfinity 2026-01-01
๐Ÿ”ฎ
๐Ÿ”ฎ Python Sets โ€” The Underrated Power of Set Operations
Python sets are unordered collections of unique elements. Set operations like union, intersection, and difference are lightning fast.
santoshtvk 2027-03-01
๐Ÿ”ข
๐Ÿ”ข NumPy Arrays
NumPy arrays are faster and more compact than Python lists. They are the foundation for scientific computing.
pynfinity 2025-04-18
๐Ÿ“œ
๐Ÿ“œ List Comprehensions
List comprehensions provide a concise way to create lists.
santoshtvk 2024-11-17
๐Ÿ”
๐Ÿ” Exploratory Data Analysis (EDA)
EDA is crucial for understanding your data. The `describe()` method gives you a quick statistical summary.
santoshtvk 2023-11-21
๐Ÿงฉ
๐Ÿงฉ Python Regex Tutorial with Examples
Regular expressions (regex) in Python use the re module to search, match, and manipulate strings with powerful pattern rules.
santoshtvk 2027-01-29
๐Ÿ“‰
๐Ÿ“‰ Matplotlib Plotting
Matplotlib is the grandfather of Python visualization libraries. It gives you control over every aspect of a figure.
santoshtvk 2025-01-11
๐ŸŽฏ
๐ŸŽฏ Python Common Interview Questions and Answers
Top Python interview questions asked at MNCs, and startups โ€” with clear answers and code examples.
santoshtvk 2025-12-18
๐Ÿš€
๐Ÿš€ Streamlit Apps
Streamlit turns data scripts into shareable web apps in minutes. All in pure Python.
pynfinity 2027-11-01
ฮป
ฮป Python Lambda Functions โ€” Small Anonymous Functions
Lambda functions are compact, one-line anonymous functions. Perfect for short operations passed to sort(), filter(), and map().
santoshtvk 2026-10-06
๐Ÿ“…
๐Ÿ“… Python datetime Module โ€” Working with Dates and Times
Python's datetime module handles dates, times, timezones, and arithmetic. Essential for logs, scheduling, and data pipelines.
santoshtvk 2026-02-20
โœจ
โœจ Jupyter Magic Commands
Magic commands are special commands that you can run in Jupyter notebooks to perform special tasks.
santoshtvk 2026-01-01
๐Ÿ—„๏ธ
๐Ÿ—„๏ธ SQLAlchemy Basics
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power of SQL.
pynfinity 2027-09-12
๐Ÿ› ๏ธ
๐Ÿ› ๏ธ Functools
The functools module is for higher-order functions: functions that act on or return other functions.
pynfinity 2024-02-20
๐Ÿšช
๐Ÿšช Python Context Managers โ€” The with Statement Explained
Context managers ensure resources (files, DB connections, locks) are always properly cleaned up, even when exceptions occur.
santoshtvk 2026-01-04
๐Ÿงน
๐Ÿงน Data Cleaning with Dropna
Missing data is a common problem. Pandas provides `dropna()` to easily remove rows or columns with null values.
santoshtvk 2023-07-17
๐ŸŒ
๐ŸŒ How to Use the requests Library in Python
The requests library is the go-to tool for making HTTP requests in Python. GET data from APIs, POST forms, handle auth โ€” all in a few lines.
santoshtvk 2024-07-02
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ Web Scraping with BeautifulSoup
BeautifulSoup helps you parse HTML and extract the data you need from websites.
pynfinity 2028-03-12
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ Web Scraping with BeautifulSoup
BeautifulSoup helps you parse HTML and extract the data you need from websites.
pynfinity 2026-01-01
๐Ÿ“Š
๐Ÿ“Š Interactive Plots with Plotly
Plotly allows you to create interactive charts that you can zoom, pan, and hover over.
santoshtvk 2026-01-01
๐Ÿ“
๐Ÿ“ Python logging Module โ€” Proper Application Logging
Real applications need structured logs, not print() statements. Python's logging module provides levels, formatting, and file logging.
santoshtvk 2026-12-11
๐Ÿ”
๐Ÿ” Itertools
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML.
santoshtvk 2024-08-17
๐Ÿ”„
๐Ÿ”„ Python enumerate() and zip() โ€” Cleaner Loop Patterns
enumerate() adds automatic counters to loops; zip() iterates multiple sequences together. Both eliminate messy manual indexing.
santoshtvk 2026-05-05
๐Ÿฅ’
๐Ÿฅ’ Pickle Serialization
The pickle module implements binary protocols for serializing and de-serializing a Python object structure.
pynfinity 2025-08-07
ฮป
ฮป Lambda Functions
A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression.
santoshtvk 2028-03-25
๐Ÿ—๏ธ
๐Ÿ—๏ธ Python OOP โ€” Classes, Objects, and Inheritance
Object-Oriented Programming in Python uses classes to bundle data and behaviour together. Master classes, inheritance, and dunder methods.
santoshtvk 2026-12-26
๐Ÿค–
๐Ÿค– Scikit-Learn Linear Regression
Linear Regression is the 'Hello World' of Machine Learning. Scikit-Learn makes it a breeze to implement.
pynfinity 2027-07-19
โš”๏ธ
โš”๏ธ FastAPI vs Flask โ€” Which Should You Choose?
FastAPI and Flask are two of Python's most popular web frameworks. Here's a clear side-by-side comparison with real code examples.
santoshtvk 2024-01-15
๐Ÿ“
๐Ÿ“ NLTK Tokenization
Tokenization is the first step in NLP. It breaks text down into words or sentences.
santoshtvk 2025-04-06
๐Ÿ“Š
๐Ÿ“Š CSV Processing
The csv module implements classes to read and write tabular data in CSV format.
santoshtvk 2023-06-14
๐Ÿง 
๐Ÿง  TensorFlow Basics
TensorFlow is a powerful library for numerical computation and large-scale machine learning.
santoshtvk 2027-12-16
๐Ÿ”ฅ
๐Ÿ”ฅ PyTorch Tensors
PyTorch tensors are similar to NumPy arrays but can run on GPUs for accelerated computing.
pynfinity 2027-06-12
๐Ÿ’ป
๐Ÿ’ป Argparse CLI
The argparse module makes it easy to write user-friendly command-line interfaces.
santoshtvk 2023-02-04
๐Ÿงช
๐Ÿงช Pytest Testing
Pytest is a framework that makes building simple and scalable tests easy.
santoshtvk 2025-10-19
๐Ÿ”
๐Ÿ” Exploratory Data Analysis (EDA)
EDA is crucial for understanding your data. The `describe()` method gives you a quick statistical summary.
santoshtvk 2026-01-01
โšก
โšก Python List Comprehension Examples
List comprehensions are Python's elegant one-liner loops. Write cleaner, faster code with this powerful feature.
santoshtvk 2026-11-12
๐Ÿ›ก๏ธ
๐Ÿ›ก๏ธ Python Error Handling โ€” try, except, finally Explained
Proper exception handling makes your Python code robust and production-ready. Learn try/except/finally with real-world patterns.
santoshtvk 2026-06-14
โœ๏ธ
Write a New Post
๐Ÿ’Ž

Bits โ€” Quick Code Snippets

๐Ÿ—บ๏ธ Folium Maps
๐Ÿ—บ๏ธ Folium Maps
๐Ÿ“ฆ Dataclasses
๐Ÿ“ฆ Dataclasses
๐Ÿ” Itertools
๐Ÿ” Itertools
๐Ÿ—„๏ธ SQLAlchemy Basics
๐Ÿ—„๏ธ SQLAlchemy Basics
๐Ÿ“„ JSON Handling
๐Ÿ“„ JSON Handling
๐Ÿ–ฅ๏ธ OS Module
๐Ÿ–ฅ๏ธ OS Module
๐Ÿ”ข NumPy Arrays
๐Ÿ”ข NumPy Arrays
โšก Generators
โšก Generators
๐Ÿผ Pandas DataFrames
๐Ÿผ Pandas DataFrames
๐ŸŽ›๏ธ Multiprocessing
๐ŸŽ›๏ธ Multiprocessing
โšก FastAPI Endpoints
โšก FastAPI Endpoints
๐Ÿ“œ List Comprehensions
๐Ÿ“œ List Comprehensions
๐Ÿชต Logging
๐Ÿชต Logging
๐Ÿš€ Streamlit Apps
๐Ÿš€ Streamlit Apps
๐Ÿงช Pytest Testing
๐Ÿงช Pytest Testing
๐Ÿง  TensorFlow Basics
๐Ÿง  TensorFlow Basics
๐ŸŒฒ Git Basics
๐ŸŒฒ Git Basics
๐Ÿ“ฆ Virtual Environments
๐Ÿ“ฆ Virtual Environments
๐Ÿท๏ธ Type Hinting
๐Ÿท๏ธ Type Hinting
๐Ÿšช Context Managers
๐Ÿšช Context Managers
๐Ÿ› ๏ธ Functools
๐Ÿ› ๏ธ Functools
๐Ÿงฉ Regular Expressions
๐Ÿงฉ Regular Expressions
๐ŸŽ€ Decorators
๐ŸŽ€ Decorators
๐Ÿ“ธ OpenCV Image Reading
๐Ÿ“ธ OpenCV Image Reading
๐Ÿ’ป Argparse CLI
๐Ÿ’ป Argparse CLI
๐Ÿ›ก๏ธ Pydantic Models
๐Ÿ›ก๏ธ Pydantic Models
๐Ÿ“š Collections Module
๐Ÿ“š Collections Module
๐Ÿ“ NLTK Tokenization
๐Ÿ“ NLTK Tokenization
๐Ÿ“‰ Matplotlib Plotting
๐Ÿ“‰ Matplotlib Plotting
๐Ÿ”ฅ Seaborn Heatmaps
๐Ÿ”ฅ Seaborn Heatmaps
๐Ÿงต Multithreading
๐Ÿงต Multithreading
โณ AsyncIO
โณ AsyncIO
๐Ÿ”ฅ PyTorch Tensors
๐Ÿ”ฅ PyTorch Tensors
โš™๏ธ Sys Module
โš™๏ธ Sys Module
โ˜๏ธ AWS S3 with Boto3
โ˜๏ธ AWS S3 with Boto3
๐Ÿฅ’ Pickle Serialization
๐Ÿฅ’ Pickle Serialization
๐Ÿ•ธ๏ธ NetworkX Graphs
๐Ÿ•ธ๏ธ NetworkX Graphs
โž— Math Module
โž— Math Module
ฮป Lambda Functions
ฮป Lambda Functions
๐Ÿ“Š CSV Processing
๐Ÿ“Š CSV Processing
๐Ÿณ Dockerfiles
๐Ÿณ Dockerfiles
๐Ÿ“‰ Statsmodels OLS
๐Ÿ“‰ Statsmodels OLS
+ New Post

Understanding Memory Management in Python

Welcome to your in-depth guide on how Python handles memory! As a beginner, you might not think about memory much, as Python does a lot of the heavy lifting for you. However, understanding what's happening behind the scenes is crucial for writing efficient and robust code, especially as you start working on larger projects.

Let's dive deep into the world of Python's memory management.


1. The Basics: Everything is an Object

In Python, every single thing you createโ€”be it a number, a string, a list, or even a functionโ€”is an object. Each object has two key pieces of information associated with it:

  • Type: What kind of object it is (e.g., integer, string).
  • Reference Count: How many variables are currently pointing to this object.

Think of it like a balloon. The balloon is the object (the actual data in memory). The strings tied to the balloon are the variables (or references).

# Here, we create an integer object with the value 10.
# The variable 'x' is a reference to this object.
x = 10 

Now, the reference count of the object 10 is 1.

# We create another variable 'y' and point it to the same object as 'x'.
y = x 

The object 10 is still the same, but now two variables (x and y) are pointing to it. So, its reference count is 2.

This concept of reference counting is the primary way Python manages memory.


2. Python's Private Heap Space

When you run a Python program, the Python interpreter gets a block of memory from your computer's operating system. This block of memory is called the heap. Python manages this heap for its own private use.

  • Private Heap: All your Python objects and data structures are stored in this private heap.
  • Python's Memory Manager: Python has a dedicated component called the memory manager that controls this heap. Itโ€™s responsible for allocating memory for new objects and deallocating (freeing) memory for objects that are no longer needed.

You, as a programmer, don't directly control this memory. You can't, for instance, tell Python to store an object at a specific memory address. You simply create variables, and the memory manager handles the rest.

Why is this important?

This abstraction makes programming in Python much simpler and safer. You don't have to worry about manually allocating and freeing memory, which is a common source of bugs in languages like C or C++.


3. The Core of Python's Memory Management: Reference Counting

As we saw earlier, every object in memory keeps track of how many references are pointing to it. This is the most fundamental part of Python's memory management.

Hereโ€™s how it works:

  1. Creation: When an object is created, its reference count is set to 1.
  2. Increment: The reference count increases whenever a new variable points to the object. This happens during assignments (y = x), passing objects as arguments to functions, or adding objects to a list.
  3. Decrement: The reference count decreases whenever a reference is removed. This happens when a variable goes out of scope (e.g., at the end of a function), or when you explicitly reassign a variable to something else (x = 20), or use del.

What happens when the reference count reaches zero?

When an object's reference count drops to zero, it means nothing is using that object anymore. It's now considered "garbage." The Python memory manager will automatically reclaim the memory occupied by this object, making that memory available for new objects. This process is called deallocation.

Example in Action

Let's trace the reference counts in a simple example.

# 1. An object (the list [1, 2, 3]) is created.
#    Reference count of [1, 2, 3] is 1 (referenced by 'my_list').
my_list = [1, 2, 3]
print(f"Initial setup: my_list is {my_list}")

# 2. We create a new reference to the same list.
#    Reference count of [1, 2, 3] is now 2 (referenced by 'my_list' and 'another_list').
another_list = my_list
print(f"After assignment: another_list is {another_list}")

# 3. We remove one reference by reassigning 'my_list'.
#    Now, a new object (the list [4, 5, 6]) is created.
#    The reference count of [1, 2, 3] decreases to 1 (only 'another_list' points to it).
#    The reference count of [4, 5, 6] is 1.
my_list = [4, 5, 6]
print(f"After reassigning my_list: my_list is {my_list}, another_list is {another_list}")

# 4. We remove the last reference to the original list.
#    The reference count of [1, 2, 3] drops to 0.
#    The memory for [1, 2, 3] is now eligible to be freed by Python.
del another_list 
print("After deleting another_list, the original list [1, 2, 3] is gone.")

4. The Garbage Collector: A Safety Net

Reference counting is great, but it has one major weakness: cyclic references.

A cyclic reference occurs when two or more objects refer to each other.

Example of a Cyclic Reference

Imagine you have two objects, obj_a and obj_b.

class MyClass:
    def __init__(self, name):
        self.name = name
        print(f"{self.name} created.")
    def __del__(self):
        # This is a special method called a destructor.
        # Python calls it right before an object is destroyed.
        print(f"{self.name} is being destroyed!")

# Create two objects
obj_a = MyClass("Object A")
obj_b = MyClass("Object B")

# Now, let's create a cycle.
# obj_a has a reference to obj_b.
obj_a.other = obj_b
# obj_b has a reference to obj_a.
obj_b.other = obj_a 

Now, obj_a points to obj_b, and obj_b points to obj_a.

Let's see what happens if we try to delete them.

del obj_a
del obj_b

You might expect their __del__ methods to be called, right? But they won't be! Here's why:

  • When we del obj_a, the reference count of the "Object A" instance from the main program scope is removed. However, its reference count is still 1 because obj_b.other is still pointing to it.
  • Similarly, when we del obj_b, its reference count also remains 1 because obj_a.other is pointing to it.

Even though we can no longer access these objects from our code, they are still keeping each other "alive" in memory. This is a memory leak.

The Role of the Garbage Collector (GC)

To solve this problem, Python has a supplemental process called the Garbage Collector (or GC). The GC's main job is to find and clean up these cyclic references.

  • The GC periodically runs and looks for objects that are part of a reference cycle but can no longer be reached from the main program.
  • It's a "generational" garbage collector. This means it divides objects into different "generations." New objects are in the youngest generation. If an object survives a round of garbage collection, it gets promoted to an older generation.
  • Objects in older generations are scanned less frequently, which makes the process more efficient.

You can actually interact with the GC through Python's built-in gc module.

import gc

# You can see how many objects are in each generation.
print(gc.get_count()) 

# You can manually trigger a garbage collection run.
# This is usually not necessary, but can be useful for debugging.
gc.collect() 

print("Garbage collection manually triggered.")

If you run the MyClass example from before and then add gc.collect(), you will see the "is being destroyed!" messages printed, because the GC breaks the cycle and reclaims the memory.


5. Practical Implications and Best Practices

Understanding memory management helps you write better code.

  • Avoid Global Variables: Global variables live for the entire duration of the program. Overusing them can lead to high memory consumption.
  • Be Mindful of Large Data Structures: If you load a massive file into a list or dictionary, it will stay in memory. For very large datasets, consider processing data in chunks or using generators, which produce one item at a time without storing the entire sequence in memory.
  • Explicitly del when needed: If you are done with a large object that is still in scope, you can use del to remove your reference to it, potentially allowing its memory to be freed sooner.
  • Use Weak References: For caching or linking objects where you don't want to create a strong reference cycle, Python provides the weakref module. A weak reference doesn't increase an object's reference count.

Example: Generators vs. Lists

Let's say you need to process a billion numbers.

# Inefficient: Creates a list of a billion numbers in memory.
# This will likely crash your computer due to insufficient memory.
# my_numbers = [i for i in range(1_000_000_000)] 

# Efficient: Uses a generator expression.
# This creates a generator object that produces numbers on the fly.
# It only stores one number in memory at a time.
my_numbers_generator = (i for i in range(1_000_000_000))

# You can loop through it just like a list, but with minimal memory usage.
# for num in my_numbers_generator:
#     # do something with num
#     pass

Summary

Concept Description How Python Handles It
Object Allocation Creating objects and assigning them memory space. Done automatically by the Python Memory Manager within the private heap.
Reference Counting The primary mechanism for memory management. An object's memory is freed when its reference count hits 0. Automatic. The interpreter increments/decrements counts as variables are assigned or go out of scope.
Cyclic References A situation where objects refer to each other, preventing their reference counts from reaching 0. Handled by the Garbage Collector (GC), which periodically finds and cleans up these cycles.
Garbage Collector (GC) A background process that acts as a safety net to clean up reference cycles. Runs automatically. Can be controlled with the gc module if needed.
Deallocation Reclaiming memory from objects that are no longer in use. Happens automatically when reference count is zero or when the GC cleans up a cycle.

Memory management in Python is a powerful feature that makes development easier and less error-prone.


Created with โค๏ธ by Pynfinity



Pynfinity
Install Pynfinity Add to home screen for the best experience