Skip to content

Latest commit

 

History

History
961 lines (752 loc) · 26.4 KB

09_advanced_python.md

File metadata and controls

961 lines (752 loc) · 26.4 KB

09 — Advanced Python

"These are the power tools. Learn them and you'll write Python that impresses everyone."


Table of Contents


Iterators

An iterator is any object that implements:

  1. __iter__() — returns the iterator object itself.
  2. __next__() — returns the next value, raises StopIteration when done.

The Iterator Protocol

# Every for loop uses the iterator protocol under the hood:
fruits = ["apple", "banana", "cherry"]

# This:
for fruit in fruits:
    print(fruit)

# Is exactly equivalent to:
fruit_iter = iter(fruits)     # Calls fruits.__iter__()
while True:
    try:
        fruit = next(fruit_iter)  # Calls fruit_iter.__next__()
        print(fruit)
    except StopIteration:
        break

Built-in iter() and next()

nums = [10, 20, 30, 40]
it = iter(nums)

print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
print(next(it))   # 40
# print(next(it)) # ❌ StopIteration!

# next() with a default (no error)
print(next(it, "DONE"))   # DONE (safe default)

Creating a Custom Iterator

class CountUp:
    """Counts from start to end (inclusive)."""

    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self   # iter returns itself

    def __next__(self):
        if self.current > self.end:
            raise StopIteration
        value = self.current
        self.current += 1
        return value


counter = CountUp(1, 5)

for n in counter:
    print(n, end=" ")   # 1 2 3 4 5

# Can also use iter/next manually
counter2 = CountUp(10, 12)
print(next(counter2))   # 10
print(next(counter2))   # 11
print(next(counter2))   # 12
# print(next(counter2)) # StopIteration


class FibonacciIterator:
    """Infinite Fibonacci sequence iterator."""

    def __init__(self):
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        return value


fib = FibonacciIterator()
# Take first 10 Fibonacci numbers
import itertools
first_10 = list(itertools.islice(fib, 10))
print(first_10)   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Generators

A generator is a function that uses yield instead of return. It produces values lazily — one at a time, on demand. Generators are much more memory-efficient than returning a full list.

yield vs return

# Regular function — builds ENTIRE list in memory
def get_squares_list(n):
    result = []
    for i in range(n):
        result.append(i ** 2)
    return result   # Returns all at once

# Generator function — produces ONE value at a time
def get_squares_gen(n):
    for i in range(n):
        yield i ** 2  # Pauses here and returns one value

# Memory comparison
lst = get_squares_list(1_000_000)    # 8+ MB in memory!
gen = get_squares_gen(1_000_000)     # ~200 bytes (no data stored)

print(next(gen))   # 0
print(next(gen))   # 1
print(next(gen))   # 4

How Generators Work

def simple_gen():
    print("Step 1: Starting")
    yield 1
    print("Step 2: After first yield")
    yield 2
    print("Step 3: After second yield")
    yield 3
    print("Step 4: Generator exhausted")


gen = simple_gen()
print(next(gen))   # Prints "Step 1: Starting", yields 1
print(next(gen))   # Prints "Step 2: After first yield", yields 2
print(next(gen))   # Prints "Step 3: After second yield", yields 3
# print(next(gen)) # Prints "Step 4: Generator exhausted", raises StopIteration

Practical Generator Examples

# Read a huge file line by line (memory efficient)
def read_large_file(filepath):
    with open(filepath, "r") as f:
        for line in f:
            yield line.strip()

# Only one line in memory at a time!
for line in read_large_file("huge_log.txt"):
    if "ERROR" in line:
        print(line)

# Infinite number generator
def natural_numbers(start=1):
    n = start
    while True:
        yield n
        n += 1

numbers = natural_numbers()
print(next(numbers))   # 1
print(next(numbers))   # 2
# Safely take first N items
import itertools
first_5 = list(itertools.islice(natural_numbers(), 5))
print(first_5)   # [1, 2, 3, 4, 5]

# Generator pipeline (very powerful for data processing)
def parse_logs(lines):
    for line in lines:
        yield line.strip()

def filter_errors(lines):
    for line in lines:
        if "ERROR" in line:
            yield line

def format_output(lines):
    for i, line in enumerate(lines, 1):
        yield f"[{i}] {line}"

# Build the pipeline
raw_lines = ["INFO: started", "ERROR: crash", "DEBUG: ok", "ERROR: timeout"]
pipeline = format_output(filter_errors(parse_logs(raw_lines)))
for result in pipeline:
    print(result)
# [1] ERROR: crash
# [2] ERROR: timeout

Generator Expressions

# List comprehension (eager — creates full list)
squares_list = [x**2 for x in range(10)]

# Generator expression (lazy — creates no list)
squares_gen = (x**2 for x in range(10))

print(type(squares_list))  # <class 'list'>
print(type(squares_gen))   # <class 'generator'>

# Use generators when you only need to iterate once
total = sum(x**2 for x in range(1_000_000))  # Efficient!
maximum = max(x**2 for x in range(100))

# Any/all with generators — short-circuits!
has_even = any(x % 2 == 0 for x in [1, 3, 4, 7])  # Stops at 4!
all_pos = all(x > 0 for x in [1, 2, 3, -1, 5])    # Stops at -1!

send() — Two-way Communication with Generators

def accumulator():
    total = 0
    while True:
        value = yield total   # Receive value AND send current total
        if value is None:
            break
        total += value

gen = accumulator()
next(gen)           # Prime the generator (advance to first yield)
print(gen.send(10)) # Send 10, receive total: 10
print(gen.send(20)) # Send 20, receive total: 30
print(gen.send(5))  # Send 5, receive total: 35

Decorators

A decorator is a function that wraps another function to extend or modify its behavior without changing its source code.

💡 Decorators use closures and first-class functions. They are Python's answer to the Decorator Design Pattern.

The Concept

# Without decorator syntax
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

def greet(name):
    print(f"Hello, {name}!")

greet = my_decorator(greet)   # Manually wrapping
greet("Logesh")
# Before function call
# Hello, Logesh!
# After function call

# With @ decorator syntax (syntactic sugar for the same thing)
@my_decorator
def greet(name):
    print(f"Hello, {name}!")

greet("Logesh")   # Same result

Practical Decorators

import time
import functools

# 1. TIMER decorator
def timer(func):
    @functools.wraps(func)   # Preserve original function metadata!
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"[{func.__name__}] took {end - start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(0.5)
    return "Done!"

result = slow_function()   # [slow_function] took 0.5002s

# 2. LOGGER decorator
def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}({args}, {kwargs})")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result!r}")
        return result
    return wrapper

@logger
def add(a, b):
    return a + b

add(3, 4)
# Calling add((3, 4), {})
# add returned 7

# 3. RETRY decorator
def retry(max_attempts=3, delay=1.0):
    """Decorator factory — takes parameters."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_error = None
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_error = e
                    print(f"Attempt {attempt} failed: {e}")
                    if attempt < max_attempts:
                        time.sleep(delay)
            raise last_error
        return wrapper
    return decorator

@retry(max_attempts=3, delay=0.5)
def unstable_api_call():
    import random
    if random.random() < 0.7:
        raise ConnectionError("API unreachable!")
    return "Success!"

# 4. CACHE decorator (memoization)
def cache(func):
    stored = {}
    @functools.wraps(func)
    def wrapper(*args):
        if args not in stored:
            stored[args] = func(*args)
        return stored[args]
    return wrapper

@cache
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(50))   # Fast! Uses cache.

# Built-in equivalent: functools.lru_cache
from functools import lru_cache

@lru_cache(maxsize=128)
def fib_builtin(n):
    if n <= 1:
        return n
    return fib_builtin(n - 1) + fib_builtin(n - 2)

# 5. ACCESS CONTROL decorator
def require_auth(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # In real app, check session/token
        user = kwargs.get("user")
        if not user or not user.get("is_authenticated"):
            raise PermissionError("Authentication required!")
        return func(*args, **kwargs)
    return wrapper

@require_auth
def view_dashboard(user):
    return f"Dashboard for {user['name']}"

Stacking Decorators

@timer
@logger
@cache
def expensive_calculation(n):
    return sum(range(n))

# Applied bottom-up: cache(logger(timer(expensive_calculation)))
result = expensive_calculation(1000)

Closures

A closure is a function that remembers and accesses variables from its enclosing scope, even after that scope has finished executing.

Requirements for a closure:

  1. A nested function inside an outer function
  2. The inner function references a variable from the outer function
  3. The outer function returns the inner function
def make_counter(start=0, step=1):
    count = start         # This variable is "enclosed"

    def counter():
        nonlocal count    # Refer to the enclosed variable
        count += step
        return count

    return counter        # Return the inner function (closure)

# Each call creates an INDEPENDENT closure with its own 'count'
counter1 = make_counter()
counter2 = make_counter(start=10, step=5)

print(counter1())   # 1
print(counter1())   # 2
print(counter1())   # 3

print(counter2())   # 15
print(counter2())   # 20
# counter1 and counter2 are completely independent!

# Bank account using closure (encapsulation without classes)
def make_account(initial_balance):
    balance = initial_balance

    def deposit(amount):
        nonlocal balance
        balance += amount
        return balance

    def withdraw(amount):
        nonlocal balance
        if amount > balance:
            raise ValueError("Insufficient funds!")
        balance -= amount
        return balance

    def get_balance():
        return balance

    return deposit, withdraw, get_balance   # Return multiple closures

deposit, withdraw, get_balance = make_account(1000)

print(get_balance())     # 1000
print(deposit(500))      # 1500
print(withdraw(300))     # 1200
print(get_balance())     # 1200
# 'balance' is completely private — no way to access it directly!

Common Closure Pitfall — Late Binding

# ❌ Bug: closures capture variables by REFERENCE, not by value
functions = []
for i in range(5):
    functions.append(lambda: i)   # All capture the same 'i'!

print([f() for f in functions])  # [4, 4, 4, 4, 4] ← All 4!

# ✅ Fix: capture current value with default argument
functions = []
for i in range(5):
    functions.append(lambda x=i: x)  # Default arg = current value

print([f() for f in functions])  # [0, 1, 2, 3, 4] ✅

Context Managers (with statement)

A context manager manages resources automatically — it sets up on entry and tears down on exit, even if an error occurs.

⚠️ Without understanding context managers, you can't properly do file handling, database connections, locks, etc.

# The with statement calls __enter__ and __exit__
with open("file.txt", "r") as f:
    content = f.read()
# File is AUTOMATICALLY closed here, even if an error occurred inside

Creating Context Managers with Classes

class DatabaseConnection:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connection = None

    def __enter__(self):
        """Setup — called at the start of 'with' block."""
        print(f"Connecting to {self.host}:{self.port}...")
        self.connection = f"conn_{self.host}"  # Simulate connection
        return self.connection   # Bound to 'as' variable

    def __exit__(self, exc_type, exc_value, traceback):
        """Teardown — always called at the end of 'with' block."""
        print(f"Closing connection to {self.host}...")
        self.connection = None
        # If exc_type is not None, an exception occurred
        if exc_type:
            print(f"Error occurred: {exc_value}. Rolling back...")
        return False   # False = don't suppress the exception


with DatabaseConnection("localhost", 5432) as conn:
    print(f"Executing query on {conn}")
    # Error here would still close connection!

# Connecting to localhost:5432...
# Executing query on conn_localhost
# Closing connection to localhost:5432...

Creating Context Managers with contextlib

from contextlib import contextmanager

# Much simpler — just use yield!
@contextmanager
def timer_context(label=""):
    import time
    start = time.perf_counter()
    try:
        yield   # Code inside 'with' block runs here
    finally:
        end = time.perf_counter()
        print(f"{label}: {end - start:.4f}s")

@contextmanager
def temp_directory():
    import tempfile, shutil
    tmpdir = tempfile.mkdtemp()
    try:
        yield tmpdir            # Provide the temp dir
    finally:
        shutil.rmtree(tmpdir)  # Always clean up!

@contextmanager
def managed_resource(name):
    print(f"Acquiring: {name}")
    try:
        yield name
    except Exception as e:
        print(f"Error with {name}: {e}")
        raise  # Re-raise the exception
    finally:
        print(f"Releasing: {name}")


# Usage
with timer_context("My operation"):
    time.sleep(0.1)
    print("Doing work...")
# Doing work...
# My operation: 0.1001s

with temp_directory() as tmpdir:
    print(f"Working in: {tmpdir}")
    # tmpdir is automatically deleted when done

Nested Context Managers

# Traditional nesting
with open("input.txt") as infile:
    with open("output.txt", "w") as outfile:
        for line in infile:
            outfile.write(line.upper())

# Cleaner syntax (Python 3.10+)
with open("input.txt") as infile, open("output.txt", "w") as outfile:
    for line in infile:
        outfile.write(line.upper())

contextlib Utilities

from contextlib import suppress, redirect_stdout, nullcontext

# suppress — silently ignore specific exceptions
with suppress(FileNotFoundError):
    open("nonexistent.txt")   # No error raised!

# redirect_stdout — capture print output
import io
buffer = io.StringIO()
with redirect_stdout(buffer):
    print("This goes to buffer, not console")
output = buffer.getvalue()
print(f"Captured: {output!r}")

# nullcontext — placeholder context manager
def process(data, context=None):
    with (context or nullcontext()):
        # Works whether context is None or a real context manager
        print(f"Processing: {data}")

*args & **kwargs — Deep Dive

This builds on what you learned in Functions. Here we go deeper.

Decorator Pattern with *args/**kwargs

import functools

def any_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Can inspect args and kwargs before calling
        print(f"Args: {args}, Kwargs: {kwargs}")
        result = func(*args, **kwargs)
        return result
    return wrapper

@any_decorator
def my_func(a, b, c=10, d=20):
    return a + b + c + d

my_func(1, 2, d=30)
# Args: (1, 2), Kwargs: {'d': 30}

Building Flexible APIs

class QueryBuilder:
    def __init__(self, table):
        self.table = table
        self._conditions = []
        self._columns = ["*"]
        self._limit = None
        self._order = None

    def select(self, *columns):
        self._columns = list(columns)
        return self   # Method chaining!

    def where(self, **conditions):
        for key, value in conditions.items():
            self._conditions.append(f"{key} = '{value}'")
        return self

    def limit(self, n):
        self._limit = n
        return self

    def order_by(self, column, direction="ASC"):
        self._order = f"{column} {direction}"
        return self

    def build(self):
        sql = f"SELECT {', '.join(self._columns)} FROM {self.table}"
        if self._conditions:
            sql += f" WHERE {' AND '.join(self._conditions)}"
        if self._order:
            sql += f" ORDER BY {self._order}"
        if self._limit:
            sql += f" LIMIT {self._limit}"
        return sql

# Fluent interface powered by **kwargs
query = (QueryBuilder("users")
         .select("name", "email", "age")
         .where(role="admin", is_active="true")
         .order_by("name")
         .limit(10)
         .build())

print(query)
# SELECT name, email, age FROM users WHERE role = 'admin' AND is_active = 'true' ORDER BY name ASC LIMIT 10

Forwarding Args

def log_and_call(func, *args, **kwargs):
    """Call any function with any arguments, logging them."""
    print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
    return func(*args, **kwargs)

def add(x, y):
    return x + y

result = log_and_call(add, 3, 4)
result = log_and_call(print, "hello", "world", sep=", ", end="!\n")

Dataclasses (@dataclass)

A dataclass automatically generates __init__, __repr__, __eq__, and more from field annotations.

from dataclasses import dataclass, field, asdict, astuple
from typing import ClassVar

@dataclass
class Student:
    name: str
    age: int
    grade: float = 0.0             # Default value
    subjects: list = field(default_factory=list)  # Mutable default!
    school: ClassVar[str] = "Python Academy"       # Class variable

    def is_passing(self) -> bool:
        return self.grade >= 60.0

# Auto-generated __init__
s1 = Student("Logesh", 22, 85.5)
s2 = Student("Alice", 20)

# Auto-generated __repr__
print(s1)   # Student(name='Logesh', age=22, grade=85.5, subjects=[])

# Auto-generated __eq__
s3 = Student("Logesh", 22, 85.5)
print(s1 == s3)  # True

# Convert to dict or tuple
print(asdict(s1))      # {'name': 'Logesh', 'age': 22, 'grade': 85.5, ...}
print(astuple(s1))     # ('Logesh', 22, 85.5, [])

# Frozen dataclass (immutable — generates __hash__ too)
@dataclass(frozen=True)
class Point:
    x: float
    y: float

p = Point(3.0, 4.0)
# p.x = 5.0  # ❌ FrozenInstanceError

# Order=True — generates __lt__, __gt__ for sorting
@dataclass(order=True)
class Product:
    sort_index: float = field(init=False, repr=False)
    name: str
    price: float

    def __post_init__(self):
        self.sort_index = self.price  # Sort by price

products = [Product("Apple", 1.5), Product("Mango", 3.0), Product("Banana", 2.0)]
products.sort()
print([p.name for p in products])  # ['Apple', 'Banana', 'Mango']

__slots__ — Memory Optimization

# Normal class — each instance has a __dict__ (overhead: ~240 bytes)
class NormalPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = NormalPoint(1, 2)
print(p.__dict__)      # {'x': 1, 'y': 2}
p.z = 3               # Can add ANY attribute dynamically

# With __slots__ — fixed attributes, no __dict__ (~120 bytes saved per instance!)
class SlottedPoint:
    __slots__ = ["x", "y"]   # Only these attributes allowed

    def __init__(self, x, y):
        self.x = x
        self.y = y

sp = SlottedPoint(1, 2)
# sp.z = 3    # ❌ AttributeError — z not in __slots__
# print(sp.__dict__)  # ❌ AttributeError — no __dict__!

# When to use __slots__:
# ✅ Creating millions of instances (e.g., ORM rows, game entities)
# ✅ When you know all attributes upfront
# ❌ Don't use if you need dynamic attributes
import sys
print(sys.getsizeof(p))    # ~48 bytes
print(sys.getsizeof(sp))   # ~32 bytes (smaller!)

functools.partial — Freeze Function Arguments

from functools import partial

def power(base, exponent):
    return base ** exponent

# Create specialized versions with one argument fixed
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(5))   # 25
print(cube(3))     # 27

# Practical: pre-configure print() with custom sep/end
print_dash = partial(print, sep=" | ", end="\n---\n")
print_dash("Name", "Age", "City")
# Name | Age | City
# ---

# Practical: pre-configure a request with base URL and headers
import functools
def make_request(url, method="GET", headers=None, timeout=30):
    print(f"{method} {url} (timeout={timeout})")

api_get = partial(make_request, method="GET", headers={"Auth": "Bearer token"})
api_get("https://api.example.com/users")
api_get("https://api.example.com/posts")

functools.singledispatch — Function Overloading

from functools import singledispatch

# simulated method overloading based on argument type
@singledispatch
def process(data):
    raise NotImplementedError(f"Cannot process type: {type(data)}")

@process.register(str)
def _(data):
    return f"String: {data.upper()}"

@process.register(int)
def _(data):
    return f"Integer: {data * 2}"

@process.register(list)
def _(data):
    return f"List with {len(data)} items"

@process.register(dict)
def _(data):
    return f"Dict with keys: {list(data.keys())}"

print(process("hello"))         # String: HELLO
print(process(42))              # Integer: 84
print(process([1, 2, 3]))       # List with 3 items
print(process({"a": 1}))        # Dict with keys: ['a']

@property — Deep Dive

class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius   # Private by convention

    # Getter
    @property
    def celsius(self):
        return self._celsius

    # Setter — add validation
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError(f"Temperature below absolute zero! Got {value}°C")
        self._celsius = value

    # Deleter — optional
    @celsius.deleter
    def celsius(self):
        print("Deleting temperature...")
        del self._celsius

    # Computed property — no setter needed
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

    @property
    def kelvin(self):
        return self._celsius + 273.15

t = Temperature(100)
print(t.celsius)      # 100     ← calls getter
print(t.fahrenheit)   # 212.0   ← computed property
print(t.kelvin)       # 373.15

t.celsius = 25        # ← calls setter (validated)
# t.celsius = -300   # ❌ ValueError

del t.celsius         # ← calls deleter

# Properties look like attributes but have custom logic behind them!
# This is the correct Pythonic way to do encapsulation

Interview Q&A

Q1: What is the difference between an iterator and an iterable?

An iterable is any object that can be iterated over (has __iter__): list, tuple, str, dict, set. An iterator is an object that produces values one at a time (has both __iter__ and __next__). iter(iterable) converts an iterable to an iterator.

Q2: What is a generator? How is it different from a function?

A generator is a function that uses yield instead of return. Calling it returns a generator object (lazy iterator) instead of executing the body. Values are produced one at a time — the function pauses at each yield and resumes on the next call. Memory-efficient for large sequences.

Q3: What is a decorator?

A decorator is a function that wraps another function to add behavior before and/or after it, without modifying the original. Implemented via closures and the @decorator syntax. Common uses: logging, timing, caching, authentication.

Q4: What is functools.wraps and why is it important?

Without @functools.wraps(func), the wrapper function replaces the original function's __name__, __doc__, and other metadata. @wraps preserves the original metadata, which is important for debugging, documentation generation, and other decorators.

Q5: What is a closure?

A closure is an inner function that captures and remembers variables from its enclosing scope even after the outer function has returned. Used in decorators, factory functions, and partial application.

Q6: What does a context manager's __exit__ method receive?

__exit__(self, exc_type, exc_value, traceback) receives exception info if one occurred inside the with block. If no exception occurred, all three are None. Return True to suppress the exception; False (or None) to let it propagate.

Q7: When would you choose a generator over a list?

Use a generator when: (1) the dataset is too large to fit in memory; (2) you only need to iterate once; (3) you're building data pipelines; (4) you need infinite sequences. Use a list when you need random access, multiple iterations, or the len() of the result.

Q8: What is a dataclass?

@dataclass is a decorator that automatically generates __init__, __repr__, __eq__ (and optionally __lt__, __hash__) from class-level field annotations. It reduces boilerplate for classes that primarily store data.

Q9: What is __slots__ and when should you use it?

__slots__ replaces the per-instance __dict__ with a fixed set of attributes, reducing memory usage significantly. Use when creating millions of instances (games, ORMs, data processing). Don't use when you need dynamic attribute assignment.

Q10: What is functools.partial?

partial(func, *args, **kwargs) creates a new function with some arguments of func pre-filled. Useful for creating specialized versions of general functions, configuring callbacks, and avoiding repetitive argument passing.


Next: 10 — Garbage Collection →