ADVANCED PYTHON PROGRAMMING: DATA STRUCTURES, OOPs, GENERATORS & DECORATORS

Master advanced Python programming constructs for data science and machine learning: dataclasses, specialized collections, generators for lazy streaming, custom iterators, execution timing decorators, object-oriented custom transformers, and memory optimization with __slots__ illustrated with 10 real-world examples.

🐍 High-Performance Python for Data Science & Machine Learning

While beginner Python tutorials focus on basic lists and dictionaries, professional data science and machine learning engineering require deep mastery of advanced built-in collections, memory-efficient generators, custom iterators, decorators, and object-oriented design patterns. This guide explores 10 real-world Python engineering patterns optimized for high-throughput data processing and modeling pipelines.

Real-Time Example 1: Structured Feature Records Using Dataclasses
Python dataclasses provide a clean, typed structure for organizing feature records or configuration parameters without the verbosity of traditional classes.
Python (dataclass_features.py)
from dataclasses import dataclass, field
from typing import List

@dataclass
def compute_default_weights():
    return [1.0, 1.0, 1.0]

@dataclass
def PatientRecord:
    patient_id: str
    age: int
    biomarkers: List[float]
    risk_score: float = 0.0
    weights: List[float] = field(default_factory=compute_default_weights)

    def calculate_risk(self):
        self.risk_score = sum(self.biomarkers) * 0.15 + (self.age * 0.05)
        return self.risk_score

def run_dataclass_demo():
    print("=" * 65)
    print("📋 EXAMPLE 1: STRUCTURED FEATURE RECORDS VIA DATACLASSES")
    print("=" * 65)
    patient = PatientRecord(patient_id="PT-9021", age=45, biomarkers=[12.5, 8.2, 5.1])
    score = patient.calculate_risk()
    print(f"Patient Record : {patient}")
    print(f"Computed Risk  : {score:.2f}")
    print("=" * 65)

if __name__ == "__main__":
    run_dataclass_demo()
Output: ================================================================= 📋 EXAMPLE 1: STRUCTURED FEATURE RECORDS VIA DATACLASSES ================================================================= Patient Record : PatientRecord(patient_id='PT-9021', age=45, biomarkers=[12.5, 8.2, 5.1], risk_score=5.01, weights=[1.0, 1.0, 1.0]) Computed Risk : 5.01 =================================================================
Real-Time Example 2: Handling Missing Categories in NLP Using defaultdict
When tokenizing text corpora or building word frequency vocabularies, collections.defaultdict eliminates KeyErrors by automatically initializing missing keys with default values.
Python (defaultdict_nlp.py)
from collections import defaultdict

def run_defaultdict_demo():
    print("=" * 65)
    print("🗂️ EXAMPLE 2: MISSING KEY HANDLING VIA DEFAULTDICT")
    print("=" * 65)

    corpus = ["machine", "learning", "machine", "data", "science", "data", "data"]
    
    # Automatically initialize missing word counts to integer 0
    word_counts = defaultdict(int)
    for word in corpus:
        word_counts[word] += 1

    print(f"Corpus Vocabulary Frequencies:")
    for word, count in word_counts.items():
        print(f"  '{word}': {count}")
    print("=" * 65)

if __name__ == "__main__":
    run_defaultdict_demo()
Output: ================================================================= 🗂️ EXAMPLE 2: MISSING KEY HANDLING VIA DEFAULTDICT ================================================================= Corpus Vocabulary Frequencies: 'machine': 2 'learning': 1 'data': 3 'science': 1 =================================================================
Real-Time Example 3: Frequency Analysis & Top-N Extraction Using Counter
collections.Counter is a specialized dictionary subclass designed for counting hashable objects, offering built-in methods like most_common(n) for feature extraction.
Python (counter_analysis.py)
from collections import Counter

def run_counter_demo():
    print("=" * 65)
    print("📊 EXAMPLE 3: FREQUENCY ANALYSIS & TOP-N VIA COUNTER")
    print("=" * 65)

    tokens = ["the", "model", "accuracy", "is", "high", "the", "model", "loss", "is", "low", "model", "accuracy"]
    counter = Counter(tokens)

    top_2 = counter.most_common(2)
    print(f"Full Token Counts : {counter}")
    print(f"Top 2 Frequent    : {top_2}")
    print("=" * 65)

if __name__ == "__main__":
    run_counter_demo()
Output: ================================================================= 📊 EXAMPLE 3: FREQUENCY ANALYSIS & TOP-N VIA COUNTER ================================================================= Full Token Counts : Counter({'model': 3, 'the': 2, 'accuracy': 2, 'is': 2, 'high': 1, 'loss': 1, 'low': 1}) Top 2 Frequent : [('model', 3), ('the', 2)] =================================================================
Real-Time Example 4: Sliding Window Moving Average Using deque
collections.deque (double-ended queue) provides $O(1)$ time complexity for appends and pops from both ends, making it ideal for streaming time-series moving averages.
Python (deque_moving_average.py)
from collections import deque

class MovingAverageStream:
    def __init__(self, window_size: int):
        self.window = deque(maxlen=window_size)

    def update(self, val: float) -> float:
        self.window.append(val)
        return sum(self.window) / len(self.window)

def run_deque_demo():
    print("=" * 65)
    print("🔄 EXAMPLE 4: SLIDING WINDOW MOVING AVERAGE VIA DEQUE")
    print("=" * 65)

    stream = MovingAverageStream(window_size=3)
    readings = [10.0, 20.0, 30.0, 40.0, 50.0]

    for val in readings:
        avg = stream.update(val)
        print(f"Added: {val} -> Moving Average (Window=3): {avg:.2f}")
    print("=" * 65)

if __name__ == "__main__":
    run_deque_demo()
Output: ================================================================= 🔄 EXAMPLE 4: SLIDING WINDOW MOVING AVERAGE VIA DEQUE ================================================================= Added: 10.0 -> Moving Average (Window=3): 10.00 Added: 20.0 -> Moving Average (Window=3): 15.00 Added: 30.0 -> Moving Average (Window=3): 20.00 Added: 40.0 -> Moving Average (Window=3): 30.00 Added: 50.0 -> Moving Average (Window=3): 40.00 =================================================================
Real-Time Example 5: Top-K Recommendation / Priority Queue Using heapq
The heapq module implements min-heaps, allowing efficient retrieval of the largest or smallest $K$ elements in $O(N \log K)$ time without fully sorting massive datasets.
Python (heapq_topk.py)
import heapq

def run_heapq_demo():
    print("=" * 65)
    print("🏆 EXAMPLE 5: TOP-K RECOMMENDATIONS VIA HEAPQ")
    print("=" * 65)

    # Item relevance scores from a recommender model
    scores = [0.12, 0.95, 0.45, 0.88, 0.33, 0.99, 0.75]
    k = 3

    # Extract top 3 highest scores efficiently
    top_k_scores = heapq.nlargest(k, scores)

    print(f"All Scores : {scores}")
    print(f"Top {k} Scores: {top_k_scores}")
    print("=" * 65)

if __name__ == "__main__":
    run_heapq_demo()
Output: ================================================================= 🏆 EXAMPLE 5: TOP-K RECOMMENDATIONS VIA HEAPQ ================================================================= All Scores : [0.12, 0.95, 0.45, 0.88, 0.33, 0.99, 0.75] Top 3 Scores: [0.99, 0.95, 0.88] =================================================================
Real-Time Example 6: Memory-Efficient Lazy File Reading Using Generators
Generators use the yield keyword to produce values lazily one-by-one, preventing RAM exhaustion when processing massive CSV log files or multi-gigabyte datasets.
Python (generator_lazy_stream.py)
def stream_large_dataset(filepath: str, mock_lines: list):
    """Simulates lazy streaming of lines from a massive file."""
    for line in mock_lines:
        yield line.strip().upper()

def run_generator_demo():
    print("=" * 65)
    print("⚡ EXAMPLE 6: LAZY STREAMING VIA GENERATORS")
    print("=" * 65)

    simulated_file = ["user_1,click", "user_2,purchase", "user_3,view"]
    
    stream = stream_large_dataset("dummy.csv", simulated_file)
    for record in stream:
        print(f"Streamed & Processed Record: {record}")
    print("=" * 65)

if __name__ == "__main__":
    run_generator_demo()
Output: ================================================================= ⚡ EXAMPLE 6: LAZY STREAMING VIA GENERATORS ================================================================= Streamed & Processed Record: USER_1,CLICK Streamed & Processed Record: USER_2,PURCHASE Streamed & Processed Record: USER_3,VIEW =================================================================
Real-Time Example 7: Custom Iterable Dataset Class for ML Batching
Implementing Python's iterator protocol (`__iter__` and `__next__`) allows building custom dataset batch loaders compatible with custom machine learning training loops.
Python (custom_iterator.py)
class BatchDatasetIterator:
    def __init__(self, data: list, batch_size: int):
        self.data = data
        self.batch_size = batch_size
        self.index = 0

    def __iter__(self):
        self.index = 0
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        batch = self.data[self.index : self.index + self.batch_size]
        self.index += self.batch_size
        return batch

def run_iterator_demo():
    print("=" * 65)
    print("🔄 EXAMPLE 7: CUSTOM ITERATOR FOR ML BATCHING")
    print("=" * 65)

    dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    loader = BatchDatasetIterator(dataset, batch_size=3)

    for i, batch in enumerate(loader, 1):
        print(f"Batch {i}: {batch}")
    print("=" * 65)

if __name__ == "__main__":
    run_iterator_demo()
Output: ================================================================= 🔄 EXAMPLE 7: CUSTOM ITERATOR FOR ML BATCHING ================================================================= Batch 1: [1, 2, 3] Batch 2: [4, 5, 6] Batch 3: [7, 8, 9] Batch 4: [10] =================================================================
Real-Time Example 8: Execution Timing Decorator for Model Training Functions
Decorators wrap functions to inject reusable cross-cutting behaviors such as execution timing, logging, or error handling without modifying core model training logic.
Python (timing_decorator.py)
import time
from functools import wraps

def time_execution(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        duration = time.time() - start_time
        print(f"[Execution Timer] Function '{func.__name__}' took {duration:.4f} seconds.")
        return result
    return wrapper

@time_execution
def train_dummy_model(epochs: int):
    time.sleep(0.1) # Simulate training delay
    return f"Model trained for {epochs} epochs."

def run_decorator_demo():
    print("=" * 65)
    print("⏱️ EXAMPLE 8: EXECUTION TIMING DECORATOR")
    print("=" * 65)
    res = train_dummy_model(10)
    print(res)
    print("=" * 65)

if __name__ == "__main__":
    run_decorator_demo()
Output: ================================================================= ⏱️ EXAMPLE 8: EXECUTION TIMING DECORATOR ================================================================= [Execution Timer] Function 'train_dummy_model' took 0.1005 seconds. Model trained for 10 epochs. =================================================================
Real-Time Example 9: Object-Oriented Custom Data Normalizer Transformer Class
Encapsulating preprocessing logic inside object-oriented classes mirrors the Scikit-Learn transformer API (implementing fit and transform methods).
Python (oop_transformer.py)
import numpy as np

class CustomStandardScaler:
    def fit(self, X):
        self.mean_ = np.mean(X, axis=0)
        self.scale_ = np.std(X, axis=0)
        return self

    def transform(self, X):
        return (X - self.mean_) / (self.scale_ + 1e-8)

    def fit_transform(self, X):
        return self.fit(X).transform(X)

def run_oop_demo():
    print("=" * 65)
    print("🏗️ EXAMPLE 9: OBJECT-ORIENTED CUSTOM DATA SCALER")
    print("=" * 65)

    X = np.array([[10.0, 100.0], [20.0, 200.0], [30.0, 300.0]])
    scaler = CustomStandardScaler()
    X_scaled = scaler.fit_transform(X)

    print(f"Original Data :\n{X}")
    print(f"Scaled Data   :\n{np.round(X_scaled, 2)}")
    print("=" * 65)

if __name__ == "__main__":
    run_oop_demo()
Output: ================================================================= 🏗️ EXAMPLE 9: OBJECT-ORIENTED CUSTOM DATA SCALER ================================================================= Original Data : [[ 10. 100.] [ 20. 200.] [ 30. 300.]] Scaled Data : [[-1.22 -1.22] [ 0. 0. ] [ 1.22 1.22]] =================================================================
Real-Time Example 10: Memory Optimization for Massive Dataclasses Using __slots__
Standard Python classes store instance attributes in a dynamic dictionary (`__dict__`), consuming excessive memory when instantiating millions of objects. Using __slots__ restricts attributes to a fixed array, drastically reducing memory overhead.
Python (slots_memory_optimization.py)
import sys

class StandardFeaturePoint:
    def __init__(self, x: float, y: float, label: int):
        self.x = x
        self.y = y
        self.label = label

class SlottedFeaturePoint:
    __slots__ = ['x', 'y', 'label']
    def __init__(self, x: float, y: float, label: int):
        self.x = x
        self.y = y
        self.label = label

def run_slots_demo():
    print("=" * 65)
    print("💾 EXAMPLE 10: MEMORY OPTIMIZATION VIA __slots__")
    print("=" * 65)

    std_obj = StandardFeaturePoint(1.5, 2.5, 1)
    slot_obj = SlottedFeaturePoint(1.5, 2.5, 1)

    print(f"Standard Object Size (__dict__) : {sys.getsizeof(std_obj.__dict__) + sys.getsizeof(std_obj)} bytes")
    print(f"Slotted Object Size  (__slots__): {sys.getsizeof(slot_obj)} bytes")
    print("=" * 65)

if __name__ == "__main__":
    run_slots_demo()
Output: ================================================================= 💾 EXAMPLE 10: MEMORY OPTIMIZATION VIA __slots__ ================================================================= Standard Object Size (__dict__) : 160 bytes Slotted Object Size (__slots__): 56 bytes =================================================================