Skip to main content

SOLID Principles & Object-Oriented Design

Table of Contents​

  1. SOLID Principles Overview
  2. Single Responsibility Principle (SRP)
  3. Open/Closed Principle (OCP)
  4. Liskov Substitution Principle (LSP)
  5. Interface Segregation Principle (ISP)
  6. Dependency Inversion Principle (DIP)
  7. UML Diagrams
  8. Design Patterns Deep Dive
  9. Class Design Best Practices
  10. Python Object Model for OOP
  11. Type-Driven Design in Modern Python
  12. Design Patterns in Practice
  13. Senior / Principal — Real World OOP Scenarios

SOLID Principles Overview​

SOLID is an acronym representing five design principles for writing maintainable, scalable, and flexible object-oriented code:

PrincipleNameDescription
SSingle ResponsibilityA class should have only one reason to change
OOpen/ClosedOpen for extension, closed for modification
LLiskov SubstitutionObjects of superclass should be replaceable with subclass objects
IInterface SegregationClients should not be forced to depend on unused methods
DDependency InversionDepend on abstractions, not concrete implementations

Single Responsibility Principle (SRP)​

Definition​

A class should have only one reason to change, meaning it should have only one job or responsibility.

Why SRP Matters​

  • Easier testing: Fewer responsibilities = fewer test cases
  • Lower coupling: Less dependency between classes
  • Better organization: Smaller, focused classes are easier to understand
  • Improved maintainability: Changes are isolated and predictable

Anti-Pattern Example (Violating SRP)​

# ❌ BAD: This class has multiple responsibilities
class User:
def __init__(self, name: str, email: str):
self.name = name
self.email = email

def save_to_database(self):
"""Saving user data"""
# Database logic here
pass

def send_email(self):
"""Sending emails"""
# Email logic here
pass

def generate_report(self):
"""Generating reports"""
# Report generation logic
pass

def validate_data(self):
"""Validating user data"""
# Validation logic
pass

Correct Implementation (Following SRP)​

# ✅ GOOD: Each class has a single responsibility

class User:
"""Represents a user - only stores user data"""
def __init__(self, name: str, email: str):
self.name = name
self.email = email

def validate(self) -> bool:
"""Validate user data"""
return bool(self.name and self.email)


class UserRepository:
"""Handles database operations for users"""
def save(self, user: User):
"""Save user to database"""
pass

def find_by_email(self, email: str) -> User:
"""Find user by email"""
pass

def delete(self, user_id: int):
"""Delete user"""
pass


class EmailService:
"""Handles email operations"""
def send_welcome_email(self, user: User):
"""Send welcome email"""
pass

def send_password_reset(self, user: User, token: str):
"""Send password reset email"""
pass


class ReportGenerator:
"""Generates reports about users"""
def generate_user_report(self, users: list[User]) -> bytes:
"""Generate user report"""
pass

Real-World Diagram​

┌─────────────────────────────────────────────────────────────┐
│ BEFORE SRP │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────────────┐ │
│ │ User Class │ │
│ │ • validate_data() │ │
│ │ • save_to_database() │ 🔴 Multiple│
│ │ • send_email() │ Reasons│
│ │ • generate_report() │ to │
│ └─────────────────────────────────────────────┘ Change │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ AFTER SRP │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────┐ ┌─────────────┐ ┌────────────┐ │
│ │ User │───▶│UserRepository│───▶│ Database │ │
│ │ (Data) │ │ (Storage) │ │ │ │
│ └─────────┘ └─────────────┘ └────────────┘ │
│ │ │ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────┐ ┌───────────┐ │
│ │Validator│ │EmailService│ │
│ │ │ │ │ ✅ Single Reason to │
│ └─────────┘ └───────────┘ Change per class │
│ │
└─────────────────────────────────────────────────────────────┘

Interview Questions for SRP​

Q1: How do you identify when a class violates SRP?

Look for these signs:

  • Class name contains "And", "Or", or multiple concepts (e.g., UserAccountManager)
  • Methods that don't relate to each other
  • Class has multiple dependencies on unrelated classes
  • Changes to one feature require modifying the class
  • Testing requires mocking multiple unrelated behaviors

Q2: Can SRP be applied to functions?

Yes! Functions should do one thing:

# ❌ Bad
def process_user_data(data):
validate(data) # Thing 1
transform(data) # Thing 2
save_to_database(data) # Thing 3
send_notification(data) # Thing 4

# ✅ Good
def validate_user_data(data):
"""Thing 1: Validation"""
pass

def transform_user_data(data):
"""Thing 2: Transformation"""
pass

def save_user_data(data):
"""Thing 3: Storage"""
pass

def process_user(data):
"""Orchestration"""
validate_user_data(data)
transformed = transform_user_data(data)
save_user_data(transformed)
notify_user(data)

Open/Closed Principle (OCP)​

Definition​

Software entities (classes, modules, functions) should be open for extension but closed for modification.

Why OCP Matters​

  • Extensibility: Add new features without changing existing code
  • Stability: Existing code remains unchanged, reducing bugs
  • Flexibility: Adapt to new requirements easily
  • Testability: Existing tests still pass

Anti-Pattern Example (Violating OCP)​

# ❌ BAD: Adding new payment methods requires modifying this class
class PaymentProcessor:
def process_payment(self, payment_type: str, amount: float):
if payment_type == "credit_card":
# Process credit card
pass
elif payment_type == "debit_card":
# Process debit card
pass
elif payment_type == "paypal":
# Process PayPal
pass
# Every time we add a new payment type, we must modify this class!

Correct Implementation (Following OCP)​

# ✅ GOOD: Open for extension, closed for modification

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
"""Abstract payment method - closed for modification"""
@abstractmethod
def process(self, amount: float) -> bool:
pass

@abstractmethod
def validate(self) -> bool:
pass

class CreditCardPayment(PaymentMethod):
"""New payment types can be added without modifying existing code"""
def __init__(self, card_number: str, cvv: str):
self.card_number = card_number
self.cvv = cvv

def process(self, amount: float) -> bool:
# Credit card processing logic
return True

def validate(self) -> bool:
# Validation logic
return len(self.card_number) == 16

class PayPalPayment(PaymentMethod):
def __init__(self, email: str):
self.email = email

def process(self, amount: float) -> bool:
# PayPal processing logic
return True

def validate(self) -> bool:
return "@" in self.email

class CryptoPayment(PaymentMethod):
def __init__(self, wallet_address: str):
self.wallet_address = wallet_address

def process(self, amount: float) -> bool:
# Crypto processing logic
return True

def validate(self) -> bool:
return len(self.wallet_address) > 20

# Payment processor is closed for modification
class PaymentProcessor:
def __init__(self, payment_method: PaymentMethod):
self.payment_method = payment_method

def checkout(self, amount: float) -> dict:
if not self.payment_method.validate():
return {"success": False, "error": "Invalid payment"}

success = self.payment_method.process(amount)
return {"success": success, "amount": amount}

Real-World Diagram​

┌─────────────────────────────────────────────────────────────┐
│ OCP PATTERN │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ <<abstract>> │ │
│ │ PaymentMethod │ │
│ │ ───────────────────────────────── │ │
│ │ + process(amount: float): bool │ │
│ │ + validate(): bool │ │
│ └──────────────────────┬──────────────────────┘ │
│ │ │
│ ┌──────────────┼──────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ CreditCard │ │ PayPal │ │ Crypto │ │
│ │ Payment │ │ Payment │ │ Payment │ │
│ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ ✅ New payment types: Just add new classes! │
│ ❌ Modifying existing classes: Not required! │
│ │
└─────────────────────────────────────────────────────────────┘

Liskov Substitution Principle (LSP)​

Definition​

Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Why LSP Matters​

  • Correct inheritance: Subclasses behave like their parent
  • Type safety: Polymorphism works as expected
  • Predictability: Code using parent type works with all subtypes

Violation Example​

# ❌ BAD: Violates Liskov Substitution Principle
class Rectangle:
def __init__(self, width: float, height: float):
self.width = width
self.height = height

def set_width(self, width: float):
self.width = width

def set_height(self, height: float):
self.height = height

def area(self) -> float:
return self.width * self.height

class Square(Rectangle):
"""A square is NOT a proper subtype of Rectangle!"""
def __init__(self, side: float):
super().__init__(side, side)

def set_width(self, width: float):
# Square must keep width = height!
self.width = width
self.height = width

def set_height(self, height: float):
self.width = height
self.height = height

# This breaks expectations!
def increase_width(rectangle: Rectangle, amount: float):
original_area = rectangle.area()
rectangle.set_width(rectangle.width + amount)
# For a rectangle, area should increase
# For a square, behavior is unexpected!

Correct Implementation (Following LSP)​

# ✅ GOOD: Proper abstraction

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass

class Rectangle(Shape):
def __init__(self, width: float, height: float):
self.width = width
self.height = height

def area(self) -> float:
return self.width * self.height

class Square(Shape):
def __init__(self, side: float):
self.side = side

def area(self) -> float:
return self.side * self.side

# Now both can be used interchangeably through the Shape interface
def print_area(shape: Shape):
print(f"Area: {shape.area()}")

LSP Checklist​

A subclass is substitutable if it:

  • ✅ Doesn't strengthen preconditions
  • ✅ Doesn't weaken postconditions
  • ✅ Maintains invariants of parent
  • ✅ Doesn't throw new exceptions (unless parent's exceptions are extended)

Interface Segregation Principle (ISP)​

Definition​

Clients should not be forced to depend on interfaces they do not use.

Why ISP Matters​

  • Clean interfaces: Smaller, focused interfaces
  • Reduced coupling: Classes only depend on what they need
  • Better testing: Easier to mock specific interfaces
  • Flexibility: Implementations are not forced to implement unused methods

Violation Example​

# ❌ BAD: Fat interface forcing all methods on all implementations
from abc import ABC, abstractmethod

class Machine(ABC):
@abstractmethod
def print_document(self, document: str):
pass

@abstractmethod
def scan_document(self, document: str):
pass

@abstractmethod
def fax_document(self, document: str):
pass

@abstractmethod
def photocopy(self, document: str):
pass

class OldPrinter(Machine):
"""Old printer only prints - forced to implement unused methods"""
def print_document(self, document: str):
print(f"Printing: {document}")

def scan_document(self, document: str):
raise NotImplementedError("This printer can't scan!")

def fax_document(self, document: str):
raise NotImplementedError("This printer can't fax!")

def photocopy(self, document: str):
raise NotImplementedError("This printer can't photocopy!")

Correct Implementation (Following ISP)​

# ✅ GOOD: Segregated, role-based interfaces

from abc import ABC, abstractmethod

class Printer(ABC):
@abstractmethod
def print_document(self, document: str):
pass

class Scanner(ABC):
@abstractmethod
def scan_document(self, document: str):
pass

class FaxMachine(ABC):
@abstractmethod
def fax_document(self, document: str):
pass

class Photocopier(ABC):
@abstractmethod
def photocopy(self, document: str):
pass

# Simple devices implement only what they need
class SimplePrinter(Printer):
def print_document(self, document: str):
print(f"Printing: {document}")

class ScannerOnly(Scanner):
def scan_document(self, document: str):
print(f"Scanning: {document}")

# Multi-function device combines interfaces
class MultiFunctionPrinter(Printer, Scanner, FaxMachine, Photocopier):
def print_document(self, document: str):
print(f"Printing: {document}")

def scan_document(self, document: str):
print(f"Scanning: {document}")

def fax_document(self, document: str):
print(f"Faxing: {document}")

def photocopy(self, document: str):
print(f"Photocopying: {document}")

Real-World Diagram​

┌─────────────────────────────────────────────────────────────┐
│ BEFORE ISP (Fat Interface) │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────┐ │
│ │ Machine (ABC) │ │
│ │ + print_document() │ │
│ │ + scan_document() │ 🔴 Clients │
│ │ + fax_document() │ forced to │
│ │ + photocopy() │ implement │
│ └─────────────────────────────────────┘ everything │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ AFTER ISP (Segregated Interfaces) │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Printer │ │ Scanner │ │ Fax │ │Photocopier│ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │
│ └──────────────┴──────────────┴──────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ MultiFunction │ │
│ │ Printer │ ✅ Composes │
│ └─────────────────────┘ interfaces │
│ │
└─────────────────────────────────────────────────────────────┘

Dependency Inversion Principle (DIP)​

Definition​

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Why DIP Matters​

  • Decoupling: Components can be changed independently
  • Testability: Easy to mock dependencies
  • Flexibility: Swap implementations without changing client code
  • Maintainability: Changes are isolated

Anti-Pattern Example (Violating DIP)​

# ❌ BAD: High-level class depends on low-level implementation
class MySQLDatabase:
def connect(self):
pass

def query(self, sql: str):
pass

class UserService:
"""High-level class directly depends on low-level MySQLDatabase"""
def __init__(self):
self.database = MySQLDatabase() # Direct dependency!

def get_user(self, user_id: int):
self.database.connect()
# Also unsafe: SQL built with an f-string is open to SQL injection
return self.database.query(f"SELECT * FROM users WHERE id = {user_id}")

Correct Implementation (Following DIP)​

# ✅ GOOD: Depend on abstractions, not concretions

from abc import ABC, abstractmethod

# Abstraction (interface)
class Database(ABC):
@abstractmethod
def connect(self):
pass

@abstractmethod
def query(self, sql: str, params: tuple = ()):
pass

@abstractmethod
def execute(self, sql: str, params: tuple = ()):
pass

# Low-level implementations
class MySQLDatabase(Database):
def connect(self):
# MySQL connection logic
pass

def query(self, sql: str):
# Query logic
pass

def execute(self, sql: str, params: tuple = None):
# Execute logic
pass

class PostgreSQLDatabase(Database):
def connect(self):
# PostgreSQL connection logic
pass

def query(self, sql: str):
# Query logic
pass

def execute(self, sql: str, params: tuple = None):
# Execute logic
pass

# Note: a document store such as MongoDB does not fit a SQL-shaped interface.
# In real code, make the abstraction domain-shaped instead (e.g. a
# UserRepository with get_user/create_user) so any store can implement it.

# High-level module depends on abstraction
class UserService:
"""High-level class depends on abstract Database interface"""
def __init__(self, database: Database): # Dependency injection
self.database = database

def get_user(self, user_id: int):
self.database.connect()
return self.database.query("SELECT * FROM users WHERE id = ?", (user_id,))

def create_user(self, user_data: dict):
self.database.connect()
return self.database.execute(
"INSERT INTO users (name, email) VALUES (?, ?)",
(user_data["name"], user_data["email"])
)

# Usage - easy to switch databases
mysql_service = UserService(MySQLDatabase())
postgres_service = UserService(PostgreSQLDatabase())

Dependency Injection Patterns​

# Pattern 1: Constructor Injection (Most Common)
class Service:
def __init__(self, repository: Repository, logger: Logger):
self.repository = repository
self.logger = logger

# Pattern 2: Setter Injection
class Service:
def set_repository(self, repository: Repository):
self.repository = repository

# Pattern 3: Method Injection
class Service:
def process(self, repository: Repository, data: dict):
return repository.save(data)

# Pattern 4: Service Locator
class ServiceLocator:
_services = {}

@classmethod
def register(cls, name: str, service):
cls._services[name] = service

@classmethod
def get(cls, name: str):
return cls._services.get(name)

Real-World Diagram​

┌─────────────────────────────────────────────────────────────┐
│ DEPENDENCY INVERSION │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────┐ │
│ │ High-Level Module │ │
│ │ UserService │ │
│ │ │ │
│ │ Depends on abstraction, not │ │
│ │ concrete implementations! │ │
│ └───────────────┬─────────────────────┘ │
│ │ depends on │
│ ▼ │
│ ┌─────────────────────────────────────┐ │
│ │ <<interface>> Database │ │
│ │ ─────────────────────────────────│ │
│ │ + connect() │ │
│ │ + query() │ │
│ │ + execute() │ │
│ └───────────────┬─────────────────────┘ │
│ │ implemented by │
│ ┌───────────┼───────────┬───────────┐ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ MySQL │ │PostgreSQL│ │ MongoDB │ │ SQLite │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

UML Diagrams​

Class Diagram​

@startuml
' Basic Class Structure
class User {
- id: int
- name: str
- email: str
+ get_full_name(): str
+ validate(): bool
}

' Abstract Class
abstract class BaseService {
+ logger: Logger
+ execute(): void
}

' Interface
interface Repository {
+ save(entity): Entity
+ find_by_id(id): Entity
+ delete(id): bool
}

' Relationships
User "1" --> "1" Repository : uses
BaseService <|-- UserService : extends
Repository <|.. UserRepository : implements

' Aggregation vs Composition
class Department {
+ employees: List<Employee>
}
class Employee {
- department: Department
}

Department "1" o-- "many" Employee : aggregate
@enduml

Class Diagram Symbols​

SymbolMeaningDescription
+PublicAccessible from anywhere
-PrivateAccessible only within class
#ProtectedAccessible in class and subclasses
~PackageAccessible within package
*ManyZero or more instances
1OneExactly one instance
0..1OptionalZero or one instance

Inheritance Hierarchy Diagram​

┌─────────────────────────────────────────────────────────────┐
│ INHERITANCE HIERARCHY │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────┐ │
│ │ <<abstract>>│ │
│ │ Shape │ │
│ └───────┬───────┘ │
│ │ │
│ ┌───────────────┼───────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Circle │ │ Rectangle │ │ Triangle │ │
│ └───────────┘ └───────────┘ └───────────┘ │
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ Relationships │ │
│ ├─────────────────────────────────────────────┤ │
│ │ • Generalization: Circle IS-A Shape │ │
│ │ • Inheritance: Triangle extends Shape │ │
│ │ • Polymorphism: Any shape can be used │ │
│ │ where Shape is expected │ │
│ └─────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Sequence Diagram​

@startuml
participant Client
participant Controller
participant Service
participant Repository
participant Database

Client -> Controller: POST /users {name, email}
Controller -> Service: create_user(data)
Service -> Service: validate(data)
Service -> Repository: save(user)
Repository -> Database: INSERT INTO users
Database --> Repository: user_id
Repository --> Service: User(id=1)
Service --> Controller: User object
Controller --> Client: 201 Created

alt validation failed
Service -> Controller: ValidationError
Controller --> Client: 400 Bad Request
end
@enduml

Component Diagram​

┌─────────────────────────────────────────────────────────────┐
│ COMPONENT ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ UI Layer │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Web │ │ Mobile │ │ Admin │ │ │
│ │ │ UI │ │ UI │ │ UI │ │ │
│ │ └────┬────┘ └────┬────┘ └────┬────┘ │ │
│ └───────┼────────────┼────────────┼──────────────────┘ │
│ │ │ │ │
│ └────────────┴─────┬──────┘ │
│ │ │
│ ┌──────────────────────────┼────────────────────────────┐ │
│ │ API Gateway │ │
│ │ (Authentication) │ │
│ └──────────────────────────┬────────────────────────────┘ │
│ │ │
│ ┌──────────────────┼──────────────────┐ │
│ │ │ │ │
│ ┌───────┴───────┐ ┌───────┴───────┐ ┌───────┴───────┐ │
│ │ User │ │ Order │ │ Payment │ │
│ │ Service │ │ Service │ │ Service │ │
│ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ │
│ │ │ │ │
│ └──────────────────┴──────────────────┘ │
│ │ │
│ ┌──────────────────────────┴────────────────────────────┐ │
│ │ Data Layer │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │PostgreSQL│ │ Redis │ │ S3 │ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Design Patterns Deep Dive​

Creational Patterns​

# ============================================
# 1. SINGLETON PATTERN
# ============================================
# Ensures only one instance exists

class Singleton:
_instance = None

def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.initialized = False
return cls._instance

def __init__(self):
if not self.initialized:
self.initialized = True
self.config = {}

# Thread-safe singleton
import threading

class ThreadSafeSingleton:
_lock = threading.Lock()
_instance = None

def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance

# Usage
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True - same instance


# ============================================
# 2. FACTORY METHOD PATTERN
# ============================================
# Creates objects without specifying exact class

from abc import ABC, abstractmethod

class Transport(ABC):
@abstractmethod
def deliver(self):
pass

class Truck(Transport):
def deliver(self):
return "Delivering by road"

class Ship(Transport):
def deliver(self):
return "Delivering by sea"

class Logistics(ABC):
@abstractmethod
def create_transport(self) -> Transport:
pass

class RoadLogistics(Logistics):
def create_transport(self) -> Transport:
return Truck()

class SeaLogistics(Logistics):
def create_transport(self) -> Transport:
return Ship()

# Usage
logistics: Logistics = RoadLogistics()
transport = logistics.create_transport()
print(transport.deliver()) # "Delivering by road"


# ============================================
# 3. ABSTRACT FACTORY PATTERN
# ============================================
# Creates families of related objects

class Button(ABC):
@abstractmethod
def render(self):
pass

class TextField(ABC):
@abstractmethod
def render(self):
pass

class WindowsButton(Button):
def render(self):
return "Windows Button"

class WindowsTextField(TextField):
def render(self):
return "Windows TextField"

class MacButton(Button):
def render(self):
return "Mac Button"

class MacTextField(TextField):
def render(self):
return "Mac TextField"

class UIFactory(ABC):
@abstractmethod
def create_button(self) -> Button:
pass

@abstractmethod
def create_textfield(self) -> TextField:
pass

class WindowsFactory(UIFactory):
def create_button(self) -> Button:
return WindowsButton()

def create_textfield(self) -> TextField:
return WindowsTextField()

class MacFactory(UIFactory):
def create_button(self) -> Button:
return MacButton()

def create_textfield(self) -> TextField:
return MacTextField()

def create_ui(factory: UIFactory):
button = factory.create_button()
textfield = factory.create_textfield()
return button.render(), textfield.render()

# Usage
windows_ui = create_ui(WindowsFactory())
mac_ui = create_ui(MacFactory())


# ============================================
# 4. BUILDER PATTERN
# ============================================
# Constructs complex objects step by step

class User:
def __init__(self):
self.name = None
self.email = None
self.age = None
self.address = None
self.phone = None

def __str__(self):
return f"User({self.name}, {self.email}, {self.age}, {self.address}, {self.phone})"

class UserBuilder:
def __init__(self):
self._user = User()

def name(self, name: str):
self._user.name = name
return self

def email(self, email: str):
self._user.email = email
return self

def age(self, age: int):
self._user.age = age
return self

def address(self, address: str):
self._user.address = address
return self

def phone(self, phone: str):
self._user.phone = phone
return self

def build(self) -> User:
return self._user

# Usage - fluent interface
user = (UserBuilder()
.name("John")
.email("john@example.com")
.age(30)
.address("123 Main St")
.phone("555-1234")
.build())


# ============================================
# 5. PROTOTYPE PATTERN
# ============================================
# Clones existing objects

import copy

class Prototype:
def clone(self):
return copy.deepcopy(self)

class Document(Prototype):
def __init__(self, title: str, content: str):
self.title = title
self.content = content

def __str__(self):
return f"Document({self.title}, {self.content[:30]}...)"

# Usage
original = Document("Original", "This is the content...")
duplicate = original.clone()
duplicate.title = "Copy"

Structural Patterns​

# ============================================
# 6. ADAPTER PATTERN
# ============================================
# Converts interface of a class into another interface

class LegacyPayment:
def make_payment(self, amount: float, currency: str):
return {"status": "success", "amount": amount}

class ModernPayment:
def pay(self, amount: float, currency: str, reference: str):
return ModernResponse(amount, currency, reference)

class ModernResponse:
def __init__(self, amount, currency, reference):
self.amount = amount
self.currency = currency
self.reference = reference

class PaymentAdapter:
"""Adapter makes ModernPayment work with LegacyPayment interface"""
def __init__(self, modern_payment: ModernPayment):
self._modern = modern_payment

def make_payment(self, amount: float, currency: str):
result = self._modern.pay(amount, currency, "AUTO-REF")
return {"status": "success", "amount": result.amount}


# ============================================
# 7. DECORATOR PATTERN
# ============================================
# Adds behavior dynamically

class Coffee:
def cost(self):
return 5.0

def description(self):
return "Coffee"

class CoffeeDecorator(Coffee):
def __init__(self, coffee: Coffee):
self._coffee = coffee

def cost(self):
return self._coffee.cost()

def description(self):
return self._coffee.description()

class MilkDecorator(CoffeeDecorator):
def cost(self):
return self._coffee.cost() + 1.5

def description(self):
return self._coffee.description() + ", Milk"

class SugarDecorator(CoffeeDecorator):
def cost(self):
return self._coffee.cost() + 0.5

def description(self):
return self._coffee.description() + ", Sugar"

# Usage
coffee = Coffee()
coffee_with_milk = MilkDecorator(coffee)
coffee_with_milk_and_sugar = SugarDecorator(MilkDecorator(Coffee()))
print(coffee_with_milk_and_sugar.description()) # "Coffee, Milk, Sugar"
print(coffee_with_milk_and_sugar.cost()) # 7.0


# ============================================
# 8. FACADE PATTERN
# ============================================
# Provides simple interface to complex subsystem

class CPU:
def freeze(self): pass
def jump(self, address): pass
def execute(self): pass

class Memory:
def load(self, position, data): pass

class HardDrive:
def read(self, sector, size): pass

class ComputerFacade:
"""Simpler interface to computer subsystem"""
def __init__(self):
self.cpu = CPU()
self.memory = Memory()
self.hard_drive = HardDrive()

def start(self):
self.cpu.freeze()
self.memory.load(0, self.hard_drive.read(0, 1024))
self.cpu.jump(0)
self.cpu.execute()

def shutdown(self):
# Cleanup operations
pass

# Usage - simple interface
computer = ComputerFacade()
computer.start()


# ============================================
# 9. PROXY PATTERN
# ============================================
# Controls access to another object

class ExpensiveObject:
def operation(self):
return "Expensive operation performed"

class ExpensiveObjectProxy:
def __init__(self):
self._real_object = None

def operation(self):
if self._real_object is None:
print("Creating expensive object...")
self._real_object = ExpensiveObject()
return self._real_object.operation()

# Usage - lazy initialization
proxy = ExpensiveObjectProxy()
proxy.operation() # Creates object only when needed

Behavioral Patterns​

# ============================================
# 10. OBSERVER PATTERN
# ============================================
# Notifies multiple objects about state changes

from abc import ABC, abstractmethod
from typing import List

class Observer(ABC):
@abstractmethod
def update(self, message: str):
pass

class Subject:
def __init__(self):
self._observers: List[Observer] = []

def attach(self, observer: Observer):
self._observers.append(observer)

def detach(self, observer: Observer):
self._observers.remove(observer)

def notify(self, message: str):
for observer in self._observers:
observer.update(message)

class NewsAgency(Subject):
def __init__(self):
super().__init__()
self._news = ""

@property
def news(self):
return self._news

@news.setter
def news(self, value):
self._news = value
self.notify(f"Breaking: {value}")

class NewsChannel(Observer):
def __init__(self, name):
self.name = name

def update(self, message: str):
print(f"{self.name} received: {message}")

# Usage
news = NewsAgency()
cnn = NewsChannel("CNN")
bbc = NewsChannel("BBC")
news.attach(cnn)
news.attach(bbc)
news.news = "Python 3.14 released!"


# ============================================
# 11. STRATEGY PATTERN
# ============================================
# Defines family of algorithms, encapsulates each

class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: float) -> bool:
pass

class CreditCardStrategy(PaymentStrategy):
def __init__(self, card_num, cvv):
self.card_num = card_num
self.cvv = cvv

def pay(self, amount: float) -> bool:
return True

class PayPalStrategy(PaymentStrategy):
def __init__(self, email):
self.email = email

def pay(self, amount: float) -> bool:
return True

class ShoppingCart:
def __init__(self):
self.items = []
self.payment_strategy = None

def add_item(self, price):
self.items.append(price)

def set_payment(self, strategy: PaymentStrategy):
self.payment_strategy = strategy

def checkout(self):
total = sum(self.items)
return self.payment_strategy.pay(total)

# Usage
cart = ShoppingCart()
cart.add_item(100)
cart.set_payment(CreditCardStrategy("1234", "123"))
cart.checkout()


# ============================================
# 12. COMMAND PATTERN
# ============================================
# Encapsulates request as an object

class Command(ABC):
@abstractmethod
def execute(self):
pass

@abstractmethod
def undo(self):
pass

class Light:
def turn_on(self): print("Light ON")
def turn_off(self): print("Light OFF")

class LightOnCommand(Command):
def __init__(self, light: Light):
self.light = light

def execute(self):
self.light.turn_on()

def undo(self):
self.light.turn_off()

class RemoteControl:
def __init__(self):
self.history = []

def execute_command(self, command: Command):
command.execute()
self.history.append(command)

def undo_last(self):
if self.history:
self.history.pop().undo()

# Usage
light = Light()
remote = RemoteControl()
remote.execute_command(LightOnCommand(light))
remote.undo_last()


# ============================================
# 13. STATE PATTERN
# ============================================
# Allows object to alter behavior when state changes

class State(ABC):
@abstractmethod
def handle(self):
pass

class ConcreteStateA(State):
def handle(self):
return "State A behavior"

class ConcreteStateB(State):
def handle(self):
return "State B behavior"

class Context:
def __init__(self):
self._state = ConcreteStateA()

def set_state(self, state: State):
self._state = state

def request(self):
return self._state.handle()

Class Design Best Practices​

Cohesion​

# High Cohesion: All methods relate to single responsibility
class UserValidator:
"""High cohesion - all methods validate user data"""
def validate_email(self, email): pass
def validate_password(self, password): pass
def validate_age(self, age): pass

# Low Cohesion: Unrelated methods in one class
class UserHelper: # Don't do this!
def validate_email(self): pass
def calculate_tax(self): pass
def generate_pdf(self): pass
def send_sms(self): pass

Coupling​

# Tight Coupling: Direct dependency
class OrderService:
def __init__(self):
self.db = MySQLDatabase() # Tight coupling!

# Loose Coupling: Depend on abstractions
class OrderService:
def __init__(self, db: Database): # Loose coupling!
self.db = db

Law of Demeter (Principle of Least Knowledge)​

# Violation: Train wreck anti-pattern
class Customer:
def get_order(self): return Order()

class Order:
def get_item(self): return Item()

# DON'T DO THIS
item_name = customer.get_order().get_item().get_name()

# DO THIS - each object only talks to its direct collaborator
class Order:
def get_item_name(self):
return self.get_item().get_name()

class Customer:
def get_order_item_name(self):
return self.get_order().get_item_name()

item_name = customer.get_order_item_name()

Interview Questions​

Q1: When should you NOT use SOLID principles?​

  • Small, disposable scripts
  • Prototypes that will be rewritten
  • Over-engineering simple CRUD apps
  • When simplicity is more valuable than extensibility

Q2: How do you balance SOLID with YAGNI (You Aren't Gonna Need It)?​

  • Start with simple code
  • Refactor to SOLID when you feel pain
  • Don't anticipate requirements that don't exist
  • SOLID helps when requirements change, but adds complexity upfront

Q3: What's the difference between composition and inheritance?​

  • Inheritance: "is-a" relationship, tight coupling
  • Composition: "has-a" relationship, loose coupling, more flexible

Q4: How do you refactor a "God Class" to follow SOLID?​

  1. Identify distinct responsibilities
  2. Extract each into its own class
  3. Use dependency injection
  4. Create facade for complex interactions
  5. Write tests for each new class

Q5: What are the SOLID principles in one sentence each?​

S — Single Responsibility: one class, one reason to change. O — Open/Closed: open for extension, closed for modification. L — Liskov Substitution: subclass objects must replace superclass objects without breaking behavior. I — Interface Segregation: don't force clients to depend on methods they don't use. D — Dependency Inversion: depend on abstractions, not concrete classes.

Q6: What is the difference between inheritance and composition?​

Inheritance: "is-a" relationship via extends — couples classes to parent implementation, fragile with deep hierarchies. Composition: "has-a" relationship via object references — more flexible, testable (swap dependencies), and preferred in modern design (prefer composition over inheritance).

Q7: What is dependency injection and why does it matter for testing?​

Dependency injection passes dependencies into a class (constructor/setter) instead of creating them inside. It decouples a class from concrete implementations, making it testable with mocks/fakes and swappable in production (DB → in-memory fake).

Q8: What is the difference between factory, abstract factory, and builder patterns?​

Factory: one method creates one product type. Abstract factory: creates families of related products without specifying concrete classes. Builder: step-by-step construction of complex objects with a fluent interface, separating construction from representation.

Q9: What is the Strategy pattern?​

Strategy defines a family of interchangeable algorithms in separate classes behind a common interface, selected at runtime. Example: payment methods (card, UPI, wallet) — the payment context delegates to the active strategy, so adding a method doesn't modify existing code (OCP).

Q10: What is the Observer pattern and where is it used?​

Observer defines one-to-many dependency: when a subject changes state, all registered observers are notified. Used in event systems, pub/sub, GUI listeners, and notifications. Python has no built-in Observer mechanism; you implement it with a list of subscriber callbacks (often weak references), or use signals libraries (e.g. blinker, Django signals) or asyncio queues.

Q11: What is the difference between an abstract class and an interface?​

Abstract class: can have state, concrete methods, and constructors; in Java/C# a class can extend only one, while Python allows inheriting from several ABCs. Interface (protocol): contract only — pure method signatures, can implement multiple. Python: use ABC (abstract base classes) for abstract methods, Protocol for structural typing.

Q12: What is a God Class anti-pattern and how do you fix it?​

A God Class accumulates too many responsibilities (data, logic, I/O) — hard to test and change. Fix: identify responsibilities, extract each to its own class (facade/repository/service split), inject dependencies, and cover each new unit with tests.

Q13: What is the Repository pattern?​

Repository abstracts data access behind a collection-like interface (get, find, save) so the domain layer doesn't depend on the DB/ORM. Swappable between SQL/NoSQL/in-memory for tests. In Python: define a protocol + SQLAlchemy implementation, inject it into services.

Q14: What is the Adapter pattern?​

Adapter converts one interface to another so incompatible classes can collaborate — e.g., wrap a legacy send_email_xml() behind a modern notify() interface. Used for integrating third-party SDKs without leaking their API into your domain.

Q15: What is the Singleton pattern and why is it controversial?​

Singleton ensures one instance globally (e.g., config, logger, DB pool). Controversial: hidden global state, hard to test, violates SRP. Modern replacement: module-level instances or DI containers that manage one instance while keeping it injectable.

Q16: What is the difference between a DTO, entity, and value object?​

DTO: plain data carrier for transfer (no behavior). Entity: object with identity and lifecycle (DB row). Value object: immutable, equality by value (e.g., Money, Email). Separating them keeps layers decoupled and models clean.

Q17: What is the Facade pattern?​

Facade provides a simplified interface to a complex subsystem. Example: an OrderService that internally coordinates inventory, payment, and shipping services — clients call one method instead of orchestrating three subsystems directly.

Q18: What is the Decorator pattern?​

Decorator wraps an object to add behavior without changing its class — recursive wrapping. Used for logging, caching, retries, and permission checks around a base service while keeping the same interface.

Q19: How do you unit test SOLID code?​

Each class is small with injected dependencies → test each in isolation with mocks/fakes for dependencies, assert behavior via its public interface, keep tests independent (no shared mutable state), and test edge cases per responsibility.

Q20: What is hexagonal architecture (Ports and Adapters)?​

Core domain logic in the center, with ports (interfaces) and adapters (implementations: DB, HTTP, CLI) on the outside. Dependencies point inward; swapping a DB or API is an adapter change. This is SOLID's DIP applied at the application level.


Python Object Model for OOP​

Q21: How does Python's MRO (C3 linearization) work, and what does super() actually call?​

Every class has a method resolution order (Class.__mro__) computed with the C3 linearization algorithm. C3 guarantees three things: a class appears before its parents, the left-to-right order of bases in the class statement is preserved, and every parent's own MRO order is preserved. Attribute lookup walks this list from left to right.

super() does not mean "my parent class". It means "the next class after the current one in the MRO of type(self)". In a diamond hierarchy this lets every class in the chain run exactly once, which is what makes cooperative multiple inheritance (mixins) work.

class Base:
def save(self) -> list[str]:
return ["Base"]


class TimestampMixin(Base):
def save(self) -> list[str]:
return ["Timestamp", *super().save()]


class AuditMixin(Base):
def save(self) -> list[str]:
return ["Audit", *super().save()]


class Order(TimestampMixin, AuditMixin):
def save(self) -> list[str]:
return ["Order", *super().save()]


print([cls.__name__ for cls in Order.__mro__])
# ['Order', 'TimestampMixin', 'AuditMixin', 'Base', 'object']

print(Order().save())
# ['Order', 'Timestamp', 'Audit', 'Base']
# TimestampMixin's super() resolved to AuditMixin, not Base.

# C3 refuses orderings that contradict a parent's MRO:
try:
class Broken(Base, TimestampMixin): # Base listed before its own subclass
pass
except TypeError as exc:
print(exc) # Cannot create a consistent method resolution order (MRO) ...

For cooperative __init__, every class must accept and forward **kwargs so that each class in the chain can take the arguments it needs:

class Repository:
def __init__(self, *, table: str, **kwargs: object) -> None:
super().__init__(**kwargs)
self.table = table


class CachingMixin:
def __init__(self, *, ttl_seconds: int = 60, **kwargs: object) -> None:
super().__init__(**kwargs)
self.ttl_seconds = ttl_seconds


class UserRepository(CachingMixin, Repository):
pass


repo = UserRepository(table="users", ttl_seconds=30)
print(repo.table, repo.ttl_seconds) # users 30

Interviewer Notes:

  • Strong answers explain that super() depends on the runtime type of self, so the same line of code in TimestampMixin can call different classes depending on who inherits from it.
  • Bonus: zero-argument super() works because the compiler creates a __class__ cell for methods that use it.

Common Mistakes:

  • Calling Base.save(self) explicitly inside a mixin; in a diamond this runs Base twice or skips siblings.
  • Writing an __init__ in one class of the chain that does not call super().__init__(), which silently breaks every class after it in the MRO.

Q22: What is the difference between __new__ and __init__, and when do you override __new__?​

__new__ is a static method (special-cased, no decorator needed) that creates and returns the instance. __init__ initializes an instance that already exists and must return None. Python calls __new__ first; if it returns an instance of cls (or a subclass), __init__ is then called on it. If __new__ returns something else, __init__ is skipped.

Override __new__ when:

  • Subclassing an immutable built-in (str, int, tuple, frozenset): the value is fixed at creation time, so __init__ is too late to change it.
  • Controlling instance creation: caching/interning, returning an existing instance, or returning a subclass chosen at runtime.
from typing import Self


class Email(str):
"""A str that is always normalized and validated."""

def __new__(cls, value: str) -> Self:
normalized = value.strip().lower()
local, sep, domain = normalized.partition("@")
if not sep or not local or "." not in domain:
raise ValueError(f"invalid email: {value!r}")
return super().__new__(cls, normalized)

@property
def domain(self) -> str:
return self.partition("@")[2]


email = Email(" Alice@Example.COM ")
print(email, email.domain, isinstance(email, str))
# alice@example.com example.com True


class Currency:
_cache: dict[str, "Currency"] = {}

def __new__(cls, code: str) -> "Currency":
code = code.upper()
if code not in cls._cache:
instance = super().__new__(cls)
instance.code = code
cls._cache[code] = instance
return cls._cache[code]

code: str


print(Currency("usd") is Currency("USD")) # True - one shared instance per code

Interviewer Notes:

  • Ask the follow-up: "Why does the Currency example not define __init__?" Because __init__ would run on every call, including when a cached instance is returned, and could reset its state.

Common Mistakes:

  • Trying to normalize a str subclass in __init__ (self = ... does nothing).
  • Using __new__ when a @classmethod factory would be clearer and easier to test.

Q23: What are descriptors, and how do property, methods, and ORM fields use them?​

A descriptor is any object, stored as a class attribute, that defines __get__, __set__, or __delete__. When you access instance.attr, Python finds the descriptor on the class and calls its __get__ instead of returning the object itself.

  • Data descriptor: defines __set__ or __delete__ (e.g. property). It wins over the instance __dict__.
  • Non-data descriptor: defines only __get__ (e.g. plain functions, functools.cached_property). The instance __dict__ wins over it.

Lookup precedence for obj.x: data descriptor on the type → obj.__dict__["x"] → non-data descriptor or plain class attribute. Plain functions are non-data descriptors, which is how obj.method becomes a bound method. cached_property relies on the precedence rule: the first access computes the value and stores it in the instance __dict__, so later accesses never reach the descriptor again.

ORM column objects (SQLAlchemy, Django model fields) use the same protocol: accessed on the class they build query expressions; accessed on an instance they return the row value.

from typing import Any, overload, Self


class Positive:
"""Reusable validated field."""

def __set_name__(self, owner: type, name: str) -> None:
self.public_name = name
self.private_name = f"_{name}"

@overload
def __get__(self, obj: None, objtype: type) -> Self: ...
@overload
def __get__(self, obj: object, objtype: type) -> float: ...
def __get__(self, obj: object | None, objtype: type | None = None) -> Any:
if obj is None:
return self # accessed on the class
return getattr(obj, self.private_name)

def __set__(self, obj: object, value: float) -> None:
if value <= 0:
raise ValueError(f"{self.public_name} must be > 0, got {value}")
setattr(obj, self.private_name, value)


class LineItem:
price = Positive()
quantity = Positive()

def __init__(self, price: float, quantity: int) -> None:
self.price = price # goes through Positive.__set__
self.quantity = quantity

@property
def total(self) -> float:
return self.price * self.quantity


item = LineItem(9.99, 3)
print(round(item.total, 2)) # 29.97
try:
item.quantity = 0
except ValueError as exc:
print(exc) # quantity must be > 0, got 0

Interviewer Notes:

  • Senior candidates connect descriptors to things they use daily: bound methods, @property, @classmethod, @staticmethod, cached_property, dataclass-style field libraries, and ORM columns.
  • __set_name__ (Python 3.6+) removes the old need to pass the attribute name into the descriptor manually.

Common Mistakes:

  • Storing the value on the descriptor itself (self.value = value), which shares one value across all instances.
  • Expecting a descriptor to work when assigned to an instance attribute; descriptors only work on the class.

Q24: __init_subclass__ vs metaclasses: how would you build a plugin registry?​

__init_subclass__ (Python 3.6+) is a hook on the parent class that runs every time a subclass is created. It covers most of what people historically used metaclasses for: registering subclasses, validating that required class attributes exist, and accepting class keyword arguments.

from typing import ClassVar


class PaymentProvider:
registry: ClassVar[dict[str, type["PaymentProvider"]]] = {}
code: ClassVar[str]

def __init_subclass__(cls, *, code: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
if code in PaymentProvider.registry:
raise TypeError(f"duplicate provider code {code!r}")
cls.code = code
PaymentProvider.registry[code] = cls

def charge(self, cents: int) -> str:
raise NotImplementedError


class StripeProvider(PaymentProvider, code="stripe"):
def charge(self, cents: int) -> str:
return f"stripe charged {cents}"


class PayPalProvider(PaymentProvider, code="paypal"):
def charge(self, cents: int) -> str:
return f"paypal charged {cents}"


def get_provider(code: str) -> PaymentProvider:
try:
return PaymentProvider.registry[code]()
except KeyError:
raise ValueError(f"unknown provider {code!r}") from None


print(sorted(PaymentProvider.registry)) # ['paypal', 'stripe']
print(get_provider("stripe").charge(500)) # stripe charged 500

Reach for a metaclass only when you must control class creation itself, for example:

  • Customizing the class namespace before the body executes (__prepare__), as enum does to detect duplicate member names.
  • Changing behavior of the class object (operators or iteration on the class, like for member in Color).
  • Frameworks that rewrite class attributes before the class exists (Django's model base, abc.ABCMeta).

Interviewer Notes:

  • The principal-level answer is "the least powerful tool that works": a decorator or __init_subclass__ first, metaclass last. Metaclasses compose badly: a class cannot inherit from two bases whose metaclasses are unrelated ("metaclass conflict").
  • Ask how the registry gets populated: only when the module defining the subclass is imported. Plugin systems need an explicit import step (or entry points).

Common Mistakes:

  • Forgetting super().__init_subclass__(**kwargs), which breaks other classes in the hierarchy that also use the hook.
  • Building a registry that silently overwrites duplicates.

Q25: What is the __eq__ / __hash__ contract, and why does defining __eq__ make objects unhashable?​

The rule is: if a == b then hash(a) == hash(b). Sets and dicts first find a bucket by hash, then compare with ==. If equal objects had different hashes, lookups would miss.

When a class defines __eq__ but not __hash__, Python sets __hash__ = None, making instances unhashable. This is deliberate: the default identity-based hash would violate the contract for your new value-based equality.

Two design choices follow:

  • Value objects (Money, Email, Coordinates): equality by value, immutable, hash computed from the same fields used by __eq__.
  • Entities (User, Order): equality and hash by a stable identity (the ID), never by mutable fields.
from dataclasses import dataclass


class MutablePoint:
def __init__(self, x: int, y: int) -> None:
self.x, self.y = x, y

def __eq__(self, other: object) -> bool:
if not isinstance(other, MutablePoint):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)


try:
{MutablePoint(1, 2)}
except TypeError as exc:
print(exc) # message contains: unhashable type: 'MutablePoint'


@dataclass(frozen=True)
class Point:
x: int
y: int # frozen + eq=True (the default) -> dataclass generates __hash__


print(Point(1, 2) in {Point(1, 2)}) # True


class Customer:
def __init__(self, customer_id: int, name: str) -> None:
self.customer_id = customer_id
self.name = name # mutable, so it must not take part in hash/eq

def __eq__(self, other: object) -> bool:
if not isinstance(other, Customer):
return NotImplemented
return self.customer_id == other.customer_id

def __hash__(self) -> int:
return hash(self.customer_id)


c = Customer(7, "Ann")
seen = {c}
c.name = "Ann Smith"
print(c in seen) # True - identity field did not change

Interviewer Notes:

  • Returning NotImplemented (not False) for unknown types lets Python try the reflected operation on the other operand.
  • Good follow-up: "What happens if you hash a mutable field and then mutate it while the object is in a set?" (The object becomes unreachable by lookup; see Q46.)

Common Mistakes:

  • Defining __hash__ over mutable fields.
  • Using @dataclass(unsafe_hash=True) on a mutable class to "fix" the TypeError.

Q26: @classmethod vs @staticmethod vs a module-level function: when do you use each?​

  • Instance method: needs instance state (self).
  • @classmethod: receives the class (cls). Use it for alternative constructors and anything that must respect subclassing, because cls is the subclass when called on a subclass.
  • @staticmethod: receives neither. It is just a function namespaced inside the class. Use it when the helper is tightly tied to the class's concept and you want it discoverable there.
  • Module-level function: often the best choice for helpers that do not need the class at all. Python modules are already namespaces.
from dataclasses import dataclass
from datetime import date
from typing import Any, Self


@dataclass
class Employee:
name: str
hired_on: date

@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
# cls(...) builds the subclass when called on a subclass
return cls(name=data["name"], hired_on=date.fromisoformat(data["hired_on"]))

@staticmethod
def is_valid_name(name: str) -> bool:
return bool(name.strip()) and len(name) <= 100

def tenure_years(self, today: date) -> int:
years = today.year - self.hired_on.year
if (today.month, today.day) < (self.hired_on.month, self.hired_on.day):
years -= 1
return years


@dataclass
class Manager(Employee):
reports: int = 0


m = Manager.from_dict({"name": "Rita", "hired_on": "2019-03-01"})
print(type(m).__name__, m.tenure_years(date(2025, 2, 28))) # Manager 5
print(Employee.is_valid_name(" ")) # False

Interviewer Notes:

  • The key insight is that a @staticmethod factory returning Employee(...) would break subclasses, while a @classmethod returning cls(...) works for them.

Common Mistakes:

  • Making every helper a @staticmethod out of Java habit.
  • Hard-coding the class name inside a classmethod (return Employee(...)), which defeats its purpose.

Q27: What do __slots__ buy you, and what do they cost?​

By default each instance stores attributes in a per-instance __dict__. Declaring __slots__ replaces that dict with fixed slots stored directly in the object.

Benefits:

  • Lower memory per instance, which matters when you hold millions of small objects (events, graph nodes, rows in memory).
  • Typos fail loudly: assigning an attribute not listed in __slots__ raises AttributeError.
  • Attribute access is usually slightly faster.

Costs:

  • No dynamic attributes and no __dict__ (unless you add "__dict__" to the slots).
  • No weak references unless you add "__weakref__".
  • A slot name cannot also have a class-level default value (ValueError: ... conflicts with class variable).
  • Multiple inheritance from two classes that both define non-empty slots fails with a layout conflict.
  • Every class in the hierarchy must define __slots__; one subclass without it brings __dict__ back.

Since Python 3.10, @dataclass(slots=True) generates the slots for you.

from dataclasses import dataclass


class PlainEvent:
def __init__(self, user_id: int, kind: str) -> None:
self.user_id = user_id
self.kind = kind


@dataclass(slots=True)
class SlottedEvent:
user_id: int
kind: str


plain = PlainEvent(1, "click")
slotted = SlottedEvent(1, "click")

print(hasattr(plain, "__dict__"), hasattr(slotted, "__dict__")) # True False

plain.kidn = "typo" # silently creates a new attribute
try:
slotted.kidn = "typo" # type: ignore[attr-defined]
except AttributeError as exc:
print("AttributeError:", exc)

Interviewer Notes:

  • Ask for a measurement approach rather than a number: tracemalloc snapshots before/after creating a large batch of objects. Memory savings depend on the Python version and attribute count.

Common Mistakes:

  • Adding __slots__ everywhere "for performance" in classes that have a few hundred instances.
  • Using sys.getsizeof(obj) to compare; it does not include the separate __dict__ object.

Q28: How does encapsulation work in Python when nothing is truly private?​

Python relies on conventions and a few mechanisms rather than access modifiers:

FormMeaning
namePublic API.
_nameInternal; "do not touch from outside". Not enforced. from module import * skips _ names.
__nameName mangling: inside class Account it becomes _Account__name. Prevents accidental subclass clashes, not access.
@propertyKeep a public attribute name while adding validation or computing the value, without changing callers.

The real encapsulation goal is protecting invariants: callers should only be able to change state through methods that keep the object valid.

class Account:
def __init__(self, owner: str, opening_balance: int = 0) -> None:
if opening_balance < 0:
raise ValueError("opening balance cannot be negative")
self.owner = owner
self._balance = opening_balance
self.__audit: list[str] = [] # stored as _Account__audit

@property
def balance(self) -> int:
return self._balance # read-only: no setter defined

def withdraw(self, amount: int) -> None:
if amount <= 0 or amount > self._balance:
raise ValueError("invalid withdrawal")
self._balance -= amount
self.__audit.append(f"withdraw {amount}")


class SavingsAccount(Account):
def __init__(self, owner: str) -> None:
super().__init__(owner)
self.__audit = "subclass value" # stored as _SavingsAccount__audit, no clash


acct = SavingsAccount("Ana")
print(sorted(k for k in vars(acct) if "audit" in k))
# ['_Account__audit', '_SavingsAccount__audit']

try:
acct.balance = 1_000_000 # type: ignore[misc]
except AttributeError as exc:
print("AttributeError:", exc)

Interviewer Notes:

  • Good answers say "we are all consenting adults" but still design so the easy path keeps invariants: read-only properties, methods that validate, and immutable value objects.

Common Mistakes:

  • Calling __name "private" in the Java sense; it is still reachable as _ClassName__name.
  • Writing Java-style get_x()/set_x() pairs instead of plain attributes that can later become properties.

Type-Driven Design in Modern Python​

Q29: Protocol vs ABC in practice: which do you use for a port, and what does @runtime_checkable actually check?​

Aspectabc.ABCtyping.Protocol
Typing styleNominal: class must inherit (or be registered)Structural: any class with matching members fits
EnforcementAt instantiation: missing abstract methods raise TypeErrorAt type-check time (mypy/pyright); no runtime check by default
Shared implementationYes, concrete helper methods are inheritedPossible if a class explicitly inherits the protocol, but rarely the point
Third-party classesMust wrap or register() themFit automatically if they have the right shape

Use a Protocol for ports owned by the consumer ("I need something with send(to, body)"), especially when implementations live in other packages or are test fakes. Use an ABC when you want a base class with shared behavior and a hard runtime guarantee that subclasses implement the abstract methods.

@runtime_checkable lets you call isinstance(obj, Proto), but it only checks that the members exist. It does not check signatures, argument types, or return types.

from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable


@runtime_checkable
class Notifier(Protocol):
def send(self, to: str, body: str) -> None: ...


class SmtpNotifier: # no inheritance needed
def send(self, to: str, body: str) -> None:
print(f"email to {to}: {body}")


class BrokenNotifier:
def send(self) -> int: # wrong signature
return 42


def alert_on_call(notifier: Notifier, engineer: str) -> None:
notifier.send(engineer, "Pager: checkout error rate above 5%")


alert_on_call(SmtpNotifier(), "oncall@example.com")
print(isinstance(BrokenNotifier(), Notifier)) # True - only the name "send" is checked


class ReportExporter(ABC):
def export(self, rows: list[dict[str, str]]) -> str:
header = self.header()
return header + "\n" + "\n".join(self.format_row(r) for r in rows)

def header(self) -> str:
return "# report"

@abstractmethod
def format_row(self, row: dict[str, str]) -> str: ...


class IncompleteExporter(ReportExporter):
pass


try:
IncompleteExporter() # type: ignore[abstract]
except TypeError as exc:
print("TypeError:", exc)

Interviewer Notes:

  • Senior answers mention that Protocols are the idiomatic way to express DIP in Python: the high-level module defines the Protocol it needs, and the low-level adapter never imports it.

Common Mistakes:

  • Treating isinstance(x, SomeProtocol) as proof that x is correctly implemented.
  • Defining a Protocol for every class "just in case" (an interface with one implementation and no test fakes is usually noise).

Q30: How do you build robust value objects with dataclasses?​

A value object is immutable, compared by value, and always valid after construction. dataclasses give you most of this with options:

  • frozen=True: assignments raise FrozenInstanceError; together with eq=True (the default) a __hash__ is generated.
  • slots=True (3.10+): smaller instances, no accidental new attributes.
  • kw_only=True (3.10+): forces keyword arguments, which avoids argument-order bugs.
  • field(default_factory=...): required for mutable defaults; field(default=[]) raises ValueError at class creation.
  • __post_init__: validation and normalization. In a frozen dataclass you normalize with object.__setattr__.
  • dataclasses.replace(obj, **changes): returns a modified copy instead of mutating.
from dataclasses import FrozenInstanceError, dataclass, field, replace
from decimal import Decimal


@dataclass(frozen=True, slots=True, kw_only=True)
class Money:
amount: Decimal
currency: str

def __post_init__(self) -> None:
if not isinstance(self.amount, Decimal):
raise TypeError("amount must be a Decimal (never float for money)")
if len(self.currency) != 3:
raise ValueError(f"bad currency {self.currency!r}")
object.__setattr__(self, "currency", self.currency.upper())
object.__setattr__(self, "amount", self.amount.quantize(Decimal("0.01")))

def __add__(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("cannot add different currencies")
return replace(self, amount=self.amount + other.amount)


@dataclass(slots=True)
class Cart:
items: list[Money] = field(default_factory=list) # each Cart gets its own list

def total(self, currency: str) -> Money:
result = Money(amount=Decimal("0"), currency=currency)
for item in self.items:
result = result + item
return result


price = Money(amount=Decimal("19.999"), currency="usd")
print(price) # Money(amount=Decimal('20.00'), currency='USD')

try:
price.amount = Decimal("1") # type: ignore[misc]
except FrozenInstanceError:
print("immutable")

cart = Cart()
cart.items.append(price)
cart.items.append(Money(amount=Decimal("5"), currency="USD"))
print(cart.total("USD").amount) # 25.00
print(Cart().items) # [] - not shared with the first cart

Interviewer Notes:

  • Frozen dataclasses are shallowly immutable: a frozen dataclass holding a list can still have that list mutated. Use tuples or frozenset for collection fields of value objects.
  • Mention Decimal (or integer minor units) for money; floats cannot represent most decimal fractions exactly.

Common Mistakes:

  • Validating in a separate validate() method callers can forget to call, instead of in __post_init__.
  • Assuming frozen=True makes nested objects immutable.

Q31: How do you write a type-safe generic repository with Python 3.12 generics?​

Python 3.12 (PEP 695) added inline type-parameter syntax: class Repo[T]: ... and def first[T](xs: list[T]) -> T, plus the type statement for aliases. You no longer need TypeVar declarations for the common cases. A bound ([T: HasId]) restricts which types can be used.

Generics let one implementation serve many entity types while type checkers still know that UserRepo.get() returns a User, not object.

from dataclasses import dataclass
from typing import Protocol

type EntityId = int # type alias statement (3.12+)


class HasId(Protocol):
@property
def id(self) -> EntityId: ...


class InMemoryRepository[T: HasId]:
def __init__(self) -> None:
self._items: dict[EntityId, T] = {}

def add(self, item: T) -> None:
if item.id in self._items:
raise ValueError(f"duplicate id {item.id}")
self._items[item.id] = item

def get(self, item_id: EntityId) -> T | None:
return self._items.get(item_id)

def list_all(self) -> list[T]:
return list(self._items.values())


@dataclass(frozen=True)
class User:
id: EntityId
email: str


@dataclass(frozen=True)
class Invoice:
id: EntityId
total_cents: int


users = InMemoryRepository[User]()
users.add(User(id=1, email="a@example.com"))
found = users.get(1) # type checker infers: User | None
print(found.email if found else "missing")

invoices = InMemoryRepository[Invoice]()
invoices.add(Invoice(id=10, total_cents=4_500))
print(sum(i.total_cents for i in invoices.list_all())) # 4500

Interviewer Notes:

  • With PEP 695 syntax, variance of type parameters is inferred by the type checker, so you do not declare covariant=True manually.
  • Ask why the bound is a Protocol rather than a base class: entities do not need to inherit anything to be storable.

Common Mistakes:

  • Using Any in the repository API, which turns off checking for every caller.
  • Mixing old TypeVar declarations and new syntax for the same parameter in one class.

Q32: How do you model a state machine with Enum and make the type checker enforce that every state is handled?​

Put behavior on the enum (allowed transitions) and use match with typing.assert_never (Python 3.11+) in the case _ branch. If someone adds a new member and forgets to handle it, the type checker reports an error at the assert_never call because the remaining type is no longer Never.

from enum import StrEnum
from typing import assert_never


class OrderStatus(StrEnum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
CANCELLED = "cancelled"

def can_transition_to(self, target: "OrderStatus") -> bool:
return target in _TRANSITIONS[self]


_TRANSITIONS: dict[OrderStatus, frozenset[OrderStatus]] = {
OrderStatus.PENDING: frozenset({OrderStatus.PAID, OrderStatus.CANCELLED}),
OrderStatus.PAID: frozenset({OrderStatus.SHIPPED, OrderStatus.CANCELLED}),
OrderStatus.SHIPPED: frozenset(),
OrderStatus.CANCELLED: frozenset(),
}


def customer_message(status: OrderStatus) -> str:
match status:
case OrderStatus.PENDING:
return "Waiting for payment"
case OrderStatus.PAID:
return "Preparing your order"
case OrderStatus.SHIPPED:
return "On the way"
case OrderStatus.CANCELLED:
return "Cancelled"
case _:
assert_never(status)


print(OrderStatus.PAID.can_transition_to(OrderStatus.SHIPPED)) # True
print(OrderStatus.SHIPPED.can_transition_to(OrderStatus.PENDING)) # False
print(customer_message(OrderStatus("paid"))) # Preparing your order
print(OrderStatus.PAID == "paid") # True - StrEnum members are str instances

Interviewer Notes:

  • StrEnum (3.11+) is convenient for JSON and database columns because members are real strings. That convenience is also a risk: comparisons with arbitrary strings succeed, so validate input with OrderStatus(value) at the boundary.
  • The transition table is data, which makes it easy to test exhaustively and to render as documentation.

Common Mistakes:

  • Scattering if status == "paid" string comparisons across the codebase.
  • Using a bare case _: pass that silently ignores new states.

Q33: What is functools.singledispatch, and when is it better than isinstance chains or methods on the classes?​

singledispatch turns a function into a generic function that picks an implementation based on the type of its first argument. Implementations are registered separately, and the registration can be inferred from the type annotation. singledispatchmethod does the same for methods (dispatching on the first argument after self/cls).

It is useful for the "expression problem": you need new operations over types you cannot modify (stdlib or third-party types), so you cannot add a method to them, and you do not want a growing if isinstance(...) elif ... block.

import json
from datetime import date, datetime
from decimal import Decimal
from functools import singledispatch
from uuid import UUID


@singledispatch
def to_jsonable(value: object) -> object:
raise TypeError(f"cannot serialize {type(value).__name__}")


@to_jsonable.register
def _(value: datetime) -> str:
return value.isoformat()


@to_jsonable.register
def _(value: date) -> str: # datetime is a subclass of date; the most specific match wins
return value.isoformat()


@to_jsonable.register
def _(value: Decimal) -> str:
return str(value) # keep precision; never convert money to float


@to_jsonable.register
def _(value: UUID) -> str:
return str(value)


payload = {
"id": UUID("12345678-1234-5678-1234-567812345678"),
"amount": Decimal("10.50"),
"created": datetime(2025, 1, 2, 3, 4, 5),
"due": date(2025, 2, 1),
}
print(json.dumps(payload, default=to_jsonable))

try:
to_jsonable(object())
except TypeError as exc:
print(exc) # cannot serialize object

Interviewer Notes:

  • Dispatch follows the MRO of the argument's type, so subclasses are handled by the closest registered base.
  • Rule of thumb: if you own the classes, prefer a polymorphic method; if you do not, singledispatch keeps the operation open for extension (OCP) without touching those classes.

Common Mistakes:

  • Expecting it to dispatch on more than one argument (it does not; that is multiple dispatch).
  • Registering bool and int handlers in the wrong mental order; bool is a subclass of int, so without a bool registration, booleans go to the int handler.

Design Patterns in Practice​

Q34: What is the Unit of Work pattern, and how does it work with repositories?​

A Unit of Work (UoW) tracks everything changed during one business operation and commits it atomically, or rolls everything back. Repositories give collection-like access to aggregates; the UoW owns the transaction and hands the same connection/session to every repository involved, so "debit wallet + create order" either both persist or neither does.

The service layer depends on the UoW abstraction, which makes it trivial to swap in a fake UoW in tests. SQLAlchemy's Session is itself a unit of work; the pattern is still worth wrapping so your domain code does not depend on the ORM directly.

import sqlite3
from types import TracebackType
from typing import Self


class WalletRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn

def debit(self, user_id: int, cents: int) -> None:
cur = self.conn.execute(
"UPDATE wallets SET balance = balance - ? WHERE user_id = ? AND balance >= ?",
(cents, user_id, cents),
)
if cur.rowcount != 1:
raise ValueError("insufficient funds")


class OrderRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn

def add(self, user_id: int, cents: int) -> int:
cur = self.conn.execute(
"INSERT INTO orders (user_id, total) VALUES (?, ?)", (user_id, cents)
)
assert cur.lastrowid is not None
return cur.lastrowid


class SqliteUnitOfWork:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn

def __enter__(self) -> Self:
self.wallets = WalletRepository(self.conn)
self.orders = OrderRepository(self.conn)
return self

def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
if exc_type is None:
self.conn.commit()
else:
self.conn.rollback() # exception propagates after rollback


def place_order(uow: SqliteUnitOfWork, user_id: int, cents: int) -> int:
with uow:
order_id = uow.orders.add(user_id, cents)
uow.wallets.debit(user_id, cents) # may raise -> order insert is rolled back
return order_id


conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE wallets (user_id INTEGER PRIMARY KEY, balance INTEGER NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, total INTEGER);
INSERT INTO wallets VALUES (1, 1000);
""")

print(place_order(SqliteUnitOfWork(conn), 1, 600)) # 1
try:
place_order(SqliteUnitOfWork(conn), 1, 600) # only 400 left
except ValueError as exc:
print(exc)
print(conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]) # 1 (second insert rolled back)
print(conn.execute("SELECT balance FROM wallets").fetchone()[0]) # 400

Interviewer Notes:

  • The UoW boundary should equal the business transaction boundary, usually one use case / one request handler, not one repository call.
  • Principal follow-up: "What if the operation must also publish an event?" Write the event to an outbox table inside the same UoW and publish it asynchronously, rather than calling a broker inside the transaction.

Common Mistakes:

  • Repositories that call commit() themselves, which makes multi-repository atomicity impossible.
  • Keeping a UoW (or ORM session) open across slow network calls, holding database locks.

Q35: How do you implement Chain of Responsibility, and where do you see it in backend frameworks?​

Chain of Responsibility passes a request through a sequence of handlers; each handler either handles it (and may stop the chain) or passes it to the next. HTTP middleware (ASGI/WSGI middleware, Django middleware), logging filters, and validation pipelines are all variations of it.

In Python, the cleanest form is often composition of callables: each middleware receives the next handler and returns a new handler.

from collections.abc import Callable
from dataclasses import dataclass, field


@dataclass
class Request:
path: str
headers: dict[str, str] = field(default_factory=dict)


@dataclass
class Response:
status: int
body: str


type Handler = Callable[[Request], Response]
type Middleware = Callable[[Handler], Handler]


def auth_middleware(next_handler: Handler) -> Handler:
def handle(request: Request) -> Response:
if request.headers.get("authorization") != "Bearer secret":
return Response(401, "unauthorized") # short-circuit the chain
return next_handler(request)
return handle


def logging_middleware(next_handler: Handler) -> Handler:
def handle(request: Request) -> Response:
response = next_handler(request)
print(f"{request.path} -> {response.status}")
return response
return handle


def build_pipeline(endpoint: Handler, middlewares: list[Middleware]) -> Handler:
handler = endpoint
for middleware in reversed(middlewares): # first in list = outermost
handler = middleware(handler)
return handler


def get_orders(request: Request) -> Response:
return Response(200, "[order list]")


app = build_pipeline(get_orders, [logging_middleware, auth_middleware])
print(app(Request("/orders")).body)
print(app(Request("/orders", {"authorization": "Bearer secret"})).body)

Interviewer Notes:

  • Order matters: logging outside auth logs rejected requests too; auth outside logging hides them. Ask the candidate which order they want and why.
  • Each handler should have one responsibility (SRP), and new behavior is added by inserting a handler (OCP).

Common Mistakes:

  • Handlers that both short-circuit and also call the next handler, causing double execution.
  • Building the chain in the wrong order and being surprised by which handler runs first.

Q36: Template Method vs Strategy: what is the difference, and how do you choose?​

Both let you vary one step of an algorithm while keeping the rest fixed.

  • Template Method uses inheritance: a base class defines the skeleton method and calls abstract "hook" methods that subclasses override. The variation is fixed when you pick the subclass.
  • Strategy uses composition: the varying step is an object (or a plain function) passed in. The variation can be chosen and swapped at runtime, combined independently with other strategies, and tested in isolation.
import csv
import io
import json
from abc import ABC, abstractmethod
from collections.abc import Callable

Row = dict[str, str]


# ---- Template Method ----
class Exporter(ABC):
def export(self, rows: list[Row]) -> str: # the fixed skeleton
cleaned = [r for r in rows if r.get("status") != "deleted"]
return self.serialize(cleaned)

@abstractmethod
def serialize(self, rows: list[Row]) -> str: ...


class JsonExporter(Exporter):
def serialize(self, rows: list[Row]) -> str:
return json.dumps(rows)


# ---- Strategy ----
type Serializer = Callable[[list[Row]], str]


def to_csv(rows: list[Row]) -> str:
if not rows:
return ""
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
return buf.getvalue()


class ReportService:
def __init__(self, serializer: Serializer) -> None:
self.serializer = serializer

def export(self, rows: list[Row]) -> str:
cleaned = [r for r in rows if r.get("status") != "deleted"]
return self.serializer(cleaned)


rows = [{"id": "1", "status": "active"}, {"id": "2", "status": "deleted"}]
print(JsonExporter().export(rows))
print(ReportService(to_csv).export(rows), end="")
print(ReportService(json.dumps).export(rows)) # any matching callable is a strategy

Interviewer Notes:

  • Choose Template Method when the skeleton is stable, the variations are few, and subclasses genuinely are specializations. Choose Strategy when variations multiply, need to be combined, or are selected from configuration at runtime.
  • In Python a strategy is often just a function; a class is only needed when it carries configuration or state.

Common Mistakes:

  • Template Method hierarchies where subclasses override the skeleton method itself, defeating the pattern.
  • Creating one subclass per combination of two independent variations (format x compression), causing class explosion that Strategy avoids.

Q37: What is the Null Object pattern, and when is it better than returning None?​

A Null Object implements the same interface as a real collaborator but does nothing (or returns a neutral value). Callers no longer need if x is not None checks scattered through the code, and the "absence" behavior is defined in one place.

Good fits: optional collaborators with a safe no-op (loggers, metrics, notifiers, discount policies). Bad fit: anything where absence is an error the caller must handle (a missing user should usually raise or return None explicitly).

from decimal import Decimal
from typing import Protocol


class DiscountPolicy(Protocol):
def apply(self, subtotal: Decimal) -> Decimal: ...


class PercentageDiscount:
def __init__(self, percent: Decimal) -> None:
self.percent = percent

def apply(self, subtotal: Decimal) -> Decimal:
return subtotal * (Decimal(100) - self.percent) / Decimal(100)


class NoDiscount:
"""Null Object: neutral behavior, same interface."""

def apply(self, subtotal: Decimal) -> Decimal:
return subtotal


def lookup_discount(code: str | None) -> DiscountPolicy:
if code == "SPRING10":
return PercentageDiscount(Decimal(10))
return NoDiscount()


def checkout_total(subtotal: Decimal, code: str | None) -> Decimal:
return lookup_discount(code).apply(subtotal) # no None checks needed


print(checkout_total(Decimal("200"), "SPRING10")) # 180
print(checkout_total(Decimal("200"), None)) # 200

Interviewer Notes:

  • Ask: "When would a Null Object hide a bug?" For example a NullPaymentGateway accidentally wired in production would silently "succeed". Null Objects belong only where doing nothing is genuinely correct.

Common Mistakes:

  • Null Objects that return fake data (e.g. an empty user with id 0) that then gets persisted.

Q38: When are mixins appropriate, and what rules keep them safe?​

A mixin is a small class that adds one capability to other classes through multiple inheritance (e.g. JsonSerializableMixin, TimestampedMixin). It is not meant to be instantiated alone and does not represent an "is-a" relationship.

Rules that keep mixins maintainable:

  1. One capability per mixin, with little or no state.
  2. If it needs __init__, make it cooperative (**kwargs + super().__init__(**kwargs)), see Q21.
  3. Put mixins to the left of the main base class so their methods come first in the MRO.
  4. Document what the mixin expects from the host class (ideally as a Protocol for type checkers).
  5. If the capability does not need self state, a plain function or composition is simpler.
import json
from dataclasses import asdict, dataclass, is_dataclass
from datetime import UTC, datetime
from typing import Any


class JsonMixin:
"""Requires the host class to be a dataclass."""

def to_json(self) -> str:
if not is_dataclass(self):
raise TypeError(f"{type(self).__name__} must be a dataclass")
return json.dumps(asdict(self), default=str)


class TouchMixin:
updated_at: datetime | None

def touch(self) -> None:
self.updated_at = datetime.now(UTC)


@dataclass
class BaseModel:
id: int


@dataclass
class Article(JsonMixin, TouchMixin, BaseModel):
title: str = ""
updated_at: datetime | None = None


article = Article(id=1, title="Mixins")
article.touch()
data: dict[str, Any] = json.loads(article.to_json())
print(data["id"], data["title"], data["updated_at"] is not None) # 1 Mixins True

Interviewer Notes:

  • A senior answer weighs mixins against composition: mixins are convenient for small, orthogonal behaviors (Django class-based views use them heavily), but deep mixin stacks make it hard to know where a method comes from.

Common Mistakes:

  • Mixins with heavy state and their own non-cooperative __init__.
  • Two mixins defining the same method name without calling super(), so one silently wins.

Q39: Where should dependencies be wired together, and why is a service locator considered an anti-pattern?​

Dependency injection (Q7) says classes receive their collaborators. The composition root is the single place, close to the program's entry point (app factory, main(), worker bootstrap), where concrete implementations are created and wired. Everything below it only knows abstractions.

A service locator (a global registry that classes call to fetch their own dependencies) hides dependencies inside method bodies: you cannot see from the constructor what a class needs, tests must mutate global state, and missing registrations fail at runtime deep inside a call.

Also decide each dependency's lifetime: singleton (one per process, e.g. HTTP client, connection pool), scoped (one per request, e.g. DB session/UoW), or transient (new each time).

from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Protocol


class Clock(Protocol):
def now_iso(self) -> str: ...


class UserStore(Protocol):
def save(self, email: str, created_at: str) -> int: ...


@dataclass
class SystemClock:
def now_iso(self) -> str:
return datetime.now(UTC).isoformat()


@dataclass
class InMemoryUserStore:
rows: list[tuple[str, str]]

def save(self, email: str, created_at: str) -> int:
self.rows.append((email, created_at))
return len(self.rows)


class RegisterUser:
def __init__(self, store: UserStore, clock: Clock) -> None: # dependencies are visible
self.store = store
self.clock = clock

def __call__(self, email: str) -> int:
return self.store.save(email.lower(), self.clock.now_iso())


def build_app() -> RegisterUser:
"""Composition root: the only place that names concrete classes."""
store = InMemoryUserStore(rows=[]) # production would build a Postgres-backed store
return RegisterUser(store=store, clock=SystemClock())


# Test: wire fakes directly, no global registry to patch
@dataclass
class FixedClock:
value: str

def now_iso(self) -> str:
return self.value


store = InMemoryUserStore(rows=[])
register = RegisterUser(store, FixedClock("2025-01-01T00:00:00+00:00"))
print(register("Bob@Example.com"), store.rows)

print(build_app()("ann@example.com")) # 1

Interviewer Notes:

  • Frameworks have their own composition roots: FastAPI's Depends, Django settings plus app config, or a DI container. The principle is the same: object creation happens at the edge.
  • Principal angle: make lifetimes explicit. A request-scoped session accidentally registered as a singleton is a classic source of cross-request data leaks.

Common Mistakes:

  • Constructing concrete dependencies inside constructors "for convenience" (self.db = PostgresDB()).
  • Treating a DI container as mandatory; for most services, plain constructor calls in one factory function are enough.

Q40: How do context managers express resource ownership in Python OOP?​

A context manager ties a resource's lifetime to a block: __enter__ acquires, __exit__ releases, and __exit__ runs even when the block raises. This is Python's version of RAII and the right tool for connections, locks, files, temporary state, and transactions (see the Unit of Work in Q34).

  • __exit__ receives the exception details; returning a truthy value suppresses the exception, so almost always return None/False.
  • contextlib.contextmanager turns a generator into a context manager for simple cases.
  • contextlib.ExitStack manages a dynamic number of resources and releases them in reverse order.
  • For async resources use __aenter__/__aexit__ and async with (or contextlib.asynccontextmanager).
from collections.abc import Iterator
from contextlib import ExitStack, contextmanager


class Connection:
def __init__(self, name: str) -> None:
self.name = name
self.open = False

def __enter__(self) -> "Connection":
self.open = True
print(f"open {self.name}")
return self

def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> None:
self.open = False
print(f"close {self.name}") # runs on success and on error


@contextmanager
def feature_flag(flags: dict[str, bool], name: str, value: bool) -> Iterator[None]:
old = flags.get(name)
flags[name] = value
try:
yield
finally: # restore even if the block raises
if old is None:
flags.pop(name, None)
else:
flags[name] = old


flags: dict[str, bool] = {"new_checkout": False}
with feature_flag(flags, "new_checkout", True):
print("inside:", flags["new_checkout"])
print("after:", flags["new_checkout"])

shards = ["shard-a", "shard-b", "shard-c"]
try:
with ExitStack() as stack:
conns = [stack.enter_context(Connection(s)) for s in shards]
raise RuntimeError("query failed")
except RuntimeError as exc:
print("handled:", exc)
print([c.open for c in conns]) # [False, False, False] - closed in reverse order

Interviewer Notes:

  • Ask what happens if __enter__ raises: __exit__ is not called for that object, so acquisition must be all-or-nothing. ExitStack handles the partial case: resources entered before the failure are still released.

Common Mistakes:

  • Forgetting try/finally around yield in a @contextmanager, so cleanup is skipped on errors.
  • Returning True from __exit__ by accident and swallowing exceptions.

Senior / Principal — Real World OOP Scenarios​

Q41: Observer pattern leaks memory: disconnected WebSocket sessions are never freed​

Level: Senior

Scenario: A notification service keeps a process-wide EventBus. Each WebSocket Session object subscribes its bound method session.on_event when the client connects. After a few days the pods are OOM-killed, and logs show "send on closed socket" errors for users who disconnected hours ago.

Impact: Memory grows with every connection ever made; pods restart during peak hours and drop all live connections. CPU is wasted pushing events to dead sessions.

Root Cause: The bus stores strong references to bound methods. A bound method holds a reference to its instance (method.__self__), so the bus keeps every Session alive forever. Nothing calls unsubscribe() on disconnect, and garbage collection cannot help because the objects are still reachable.

Fix:

  1. Make subscription lifetime explicit: subscribe() returns a handle, and the session's close() path (in a finally) unsubscribes.
  2. As a safety net, store weakref.WeakMethod for bound methods so a forgotten unsubscribe cannot pin the object in memory.
  3. Add a gauge metric for subscriber count; it should track live connections, not total connections.
import gc
import weakref
from collections.abc import Callable


class EventBus:
def __init__(self) -> None:
self._handlers: dict[int, weakref.WeakMethod] = {}
self._next_id = 0

def subscribe(self, handler: Callable[[str], None]) -> int:
"""handler must be a bound method; returns a token for unsubscribe()."""
self._next_id += 1
self._handlers[self._next_id] = weakref.WeakMethod(handler)
return self._next_id

def unsubscribe(self, token: int) -> None:
self._handlers.pop(token, None)

def publish(self, event: str) -> int:
delivered = 0
for token, ref in list(self._handlers.items()):
handler = ref()
if handler is None: # owner was garbage collected
del self._handlers[token]
continue
handler(event)
delivered += 1
return delivered

def __len__(self) -> int:
return len(self._handlers)


class Session:
def __init__(self, user: str, bus: EventBus) -> None:
self.user = user
self.bus = bus
self.token = bus.subscribe(self.on_event)

def on_event(self, event: str) -> None:
pass # would write to the socket

def close(self) -> None:
self.bus.unsubscribe(self.token)


bus = EventBus()

# Explicit lifecycle (primary fix)
s1 = Session("ann", bus)
try:
print("delivered:", bus.publish("price-update")) # 1
finally:
s1.close()
print("after close:", len(bus)) # 0

# Safety net: session dropped without close() is still collectable
s2 = Session("bob", bus)
probe = weakref.ref(s2)
del s2
gc.collect()
print("session freed:", probe() is None) # True
print("delivered:", bus.publish("price-update"), len(bus)) # 0 0

Workflow Diagram:

BEFORE (strong refs) AFTER (explicit + weak refs)
┌──────────┐ bound method ┌─────────┐ ┌──────────┐ WeakMethod ┌─────────┐
│ EventBus │ ──────────────▶ │ Session │ │ EventBus │ ─ ─ ─ ─ ─ ─ ▶ │ Session │
└──────────┘ keeps alive └─────────┘ └──────────┘ no ownership └────┬────┘
│ ▲ │
▼ │ close() in finally │
sessions accumulate ──▶ OOM └──── unsubscribe(token) ◀─┘

Interviewer Notes:

  • Strong candidates name the ownership question: "who owns the subscription?" The subscriber owns it, so the subscriber must end it. Weak references are a safety net, not a substitute for lifecycle management.
  • WeakMethod exists because weakref.ref(obj.method) dies immediately: a bound method object is created fresh on each attribute access.

Red Flags:

  • "Just restart the pods nightly."
  • Calling gc.collect() in a loop to "fix" the leak.
  • Using weakref.ref(self.on_event) and wondering why handlers never fire.

Q42: Customers see each other's validation errors: shared mutable class attribute​

Level: Senior

Scenario: After a refactor, users submitting the signup form occasionally receive error messages about fields they filled in correctly, sometimes mentioning another person's email address. The bug appears only under load and never in unit tests that create one validator.

Impact: Data leakage between users (a privacy incident), confusing UX, and failed signups.

Root Cause: errors: list[str] = [] was declared at class level on a plain class. Every instance shares that single list object. self.errors.append(...) mutates the shared list rather than creating an instance attribute. A related trap is a mutable default argument (def validate(data, errors=[])), evaluated once at function definition time.

Fix:

  1. Create per-instance state in __init__ or with field(default_factory=list) in a dataclass.
  2. Prefer returning a fresh result object from a pure function over accumulating state on long-lived objects.
  3. Enable linter rules for this class of bug (Ruff's B006 flags mutable default arguments and RUF012 flags mutable class attributes) and add a test that runs two validations back to back.
from dataclasses import dataclass, field


class BuggyValidator:
errors: list[str] = [] # ONE list shared by every instance

def validate(self, email: str) -> list[str]:
if "@" not in email:
self.errors.append(f"invalid email: {email}")
return self.errors


print(BuggyValidator().validate("eve-at-example.com"))
print(BuggyValidator().validate("ann@example.com")) # still shows eve's error!


@dataclass
class ValidationResult:
errors: list[str] = field(default_factory=list) # new list per instance

@property
def ok(self) -> bool:
return not self.errors


def validate_signup(email: str, password: str) -> ValidationResult:
result = ValidationResult()
if "@" not in email:
result.errors.append("invalid email")
if len(password) < 12:
result.errors.append("password too short")
return result


print(validate_signup("eve-at-example.com", "short").errors)
print(validate_signup("ann@example.com", "a-long-passphrase").ok) # True

Workflow Diagram:

Request A ──▶ BuggyValidator() ──┐
├──▶ BuggyValidator.errors (class attr, shared) ◀── leak
Request B ──▶ BuggyValidator() ──┘

Request A ──▶ validate_signup() ──▶ ValidationResult #1 (own list)
Request B ──▶ validate_signup() ──▶ ValidationResult #2 (own list)

Interviewer Notes:

  • Ask why the bug is load-dependent: in tests each process creates few validators and resets, while in production long-lived worker processes keep accumulating into the same class-level list.
  • @dataclass refuses list / dict / set defaults with a ValueError precisely to prevent this.

Red Flags:

  • Fixing it by calling self.errors.clear() at the start of validate(); that is still shared state and races under threads.

Q43: A read replica repository breaks checkout in one region: an LSP violation​

Level: Senior

Scenario: To reduce primary database load, a team added ReplicaUserRepository(UserRepository) that reads from a replica and overrides save() to raise NotImplementedError. A config flag swaps it in for one region. Checkout in that region now returns 500s whenever it updates the user's last-order timestamp.

Impact: One region cannot complete purchases; rollback requires a config change and redeploy.

Root Cause: The subclass cannot do everything its base type promises, so it is not substitutable (Liskov Substitution Principle). Code typed against UserRepository reasonably calls save(). The type checker cannot help because the hierarchy claims the replica is a full repository.

Fix: Split the interface by capability (Interface Segregation) so that what a consumer needs is visible in its type. Read-only consumers ask for UserReader; writers ask for UserWriter. Wiring a replica into a writer becomes a type error instead of a production incident.

from dataclasses import dataclass
from typing import Protocol


@dataclass
class User:
id: int
email: str
last_order_id: int | None = None


class UserReader(Protocol):
def get(self, user_id: int) -> User | None: ...


class UserWriter(Protocol):
def save(self, user: User) -> None: ...


class PrimaryUserRepository: # satisfies both protocols
def __init__(self) -> None:
self._rows: dict[int, User] = {1: User(1, "ann@example.com")}

def get(self, user_id: int) -> User | None:
return self._rows.get(user_id)

def save(self, user: User) -> None:
self._rows[user.id] = user


class ReplicaUserRepository: # only claims what it can do
def __init__(self, primary: PrimaryUserRepository) -> None:
self._primary = primary # stands in for a replica connection

def get(self, user_id: int) -> User | None:
return self._primary.get(user_id)


class ProfilePage:
def __init__(self, users: UserReader) -> None:
self.users = users

def render(self, user_id: int) -> str:
user = self.users.get(user_id)
return user.email if user else "not found"


class Checkout:
def __init__(self, reader: UserReader, writer: UserWriter) -> None:
self.reader = reader
self.writer = writer

def complete(self, user_id: int, order_id: int) -> None:
user = self.reader.get(user_id)
if user is None:
raise LookupError(user_id)
user.last_order_id = order_id
self.writer.save(user)


primary = PrimaryUserRepository()
replica = ReplicaUserRepository(primary)

print(ProfilePage(replica).render(1)) # replica is fine for reads
Checkout(reader=primary, writer=primary).complete(1, 99)
print(primary.get(1))
# Checkout(reader=replica, writer=replica) -> mypy/pyright error: replica has no save()

Workflow Diagram:

BEFORE AFTER
UserRepository (get, save) UserReader (get) UserWriter (save)
▲ ▲ ▲ ▲
│ inherits │ │ │
ReplicaUserRepository Replica repo Primary repo ────┘
save() -> NotImplementedError ✗ │ │
│ ProfilePage Checkout(reader, writer)
Checkout calls save() ──▶ 500 (reads) wiring a replica as writer
= type-check failure ✓

Interviewer Notes:

  • A good tell for LSP violations: overrides that raise NotImplementedError, return dummy values, or add preconditions ("only works if X") that the base type did not have.
  • Read-after-write consistency is the second-order issue: a request that writes to the primary and immediately reads from a lagging replica may see stale data. Route such reads to the primary.

Red Flags:

  • "Catch NotImplementedError in Checkout and skip the save."
  • Using isinstance(repo, ReplicaUserRepository) checks inside business logic.

Q44: Refactoring a 4,000-line OrderService god class without stopping feature work​

Level: Principal

Scenario: OrderService has grown to thousands of lines and dozens of methods covering pricing, tax, inventory reservation, payment, emails, and reporting. Most incidents in the last quarter came from changes in this file, every PR conflicts with another, and nobody can say what a change will affect. Leadership will not approve a multi-month rewrite.

Impact: Slow delivery, frequent regressions, and onboarding engineers avoid the area.

Root Cause: Many responsibilities and reasons to change in one class (SRP violation), hidden coupling through shared instance state, and no tests protecting current behavior, so every refactor feels unsafe.

Fix: An incremental, strangler-style extraction (not a rewrite):

  1. Map hotspots: combine change frequency from git history with incident data to choose the first responsibility to extract (often pricing).
  2. Pin behavior with characterization tests: record current outputs for representative inputs, including odd ones, before changing anything.
  3. Extract one responsibility at a time into a class with a narrow interface; the old method stays as a one-line delegation so callers do not change.
  4. Inject the new collaborator through the constructor with a default, so tests can replace it.
  5. Migrate callers gradually, then delete the delegating method. Repeat for the next hotspot.
  6. Use code ownership and an architecture test (for example, a rule that new modules may not import order_service) to stop the class from growing back.
from dataclasses import dataclass
from decimal import Decimal


@dataclass(frozen=True)
class LineItem:
sku: str
unit_price: Decimal
quantity: int


class PricingService:
"""Extracted responsibility: only price calculation lives here."""

BULK_THRESHOLD = 10
BULK_DISCOUNT = Decimal("0.95")

def subtotal(self, items: list[LineItem]) -> Decimal:
total = Decimal("0")
for item in items:
line = item.unit_price * item.quantity
if item.quantity >= self.BULK_THRESHOLD:
line *= self.BULK_DISCOUNT
total += line
return total.quantize(Decimal("0.01"))


class OrderService:
"""Legacy facade. Public API unchanged while internals move out."""

def __init__(self, pricing: PricingService | None = None) -> None:
self.pricing = pricing or PricingService()

def calculate_subtotal(self, items: list[LineItem]) -> Decimal:
# Was 120 lines inline; now a delegation kept for existing callers.
return self.pricing.subtotal(items)

# ... remaining legacy methods are extracted one by one in later PRs


# Characterization test written BEFORE the extraction, run again after it.
def test_subtotal_characterization() -> None:
items = [
LineItem("A", Decimal("19.99"), 1),
LineItem("B", Decimal("2.50"), 10), # bulk discount applies
]
assert OrderService().calculate_subtotal(items) == Decimal("43.74")


test_subtotal_characterization()
print("characterization test passed")

Workflow Diagram:

Week 0 Week 2 Week 6+
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ OrderService │ │ OrderService │ │ OrderService │ thin
│ pricing │ ──▶ │ (delegates)──┼──▶ Pricing │ orchestrator │
│ tax │ │ tax │ └──┬──┬──┬──┬───┘
│ inventory │ │ inventory │ │ │ │ │
│ payment │ │ payment │ Pricing Tax Inventory Payment
│ email ... │ │ email ... │
└───────────────┘ └───────────────┘
characterization tests guard every step ──────────────────────────▶

Interviewer Notes:

  • Principal candidates talk about sequencing and risk: pick the extraction with the best pain-to-effort ratio, ship it in small PRs, and keep the system releasable at every step.
  • Characterization tests capture what the code does, including bugs. Fix bugs in separate, deliberate changes so behavior changes are never hidden inside refactors.

Red Flags:

  • Proposing a big-bang rewrite with a feature freeze.
  • Extracting classes that still reach back into the god class's internals (just moving the coupling around).
  • Refactoring without any tests "because the code is too tangled to test" (characterization tests through the public API are always possible).

Q45: Audit log misses changes: the fragile base class problem with a dict subclass​

Level: Senior

Scenario: A payroll service keeps runtime settings in AuditedConfig(dict), which overrides __setitem__ to write an audit entry. During a compliance review, auditors find tax-rate changes that never appeared in the audit log. Every change made through config.update(...) and through the constructor is missing.

Impact: Failed compliance audit; changes to financial settings cannot be traced.

Root Cause: The subclass depended on an implementation detail of its base class: it assumed dict.update() and dict.__init__() call __setitem__. In CPython, built-in dict methods are implemented in C and do not call overridden Python methods. This is the fragile base class problem: inheritance couples the subclass to how the parent is implemented internally, not just to its public contract.

Fix: Subclass collections.UserDict (pure Python; its update and constructor go through __setitem__), or implement collections.abc.MutableMapping with composition. Then test every mutation path, not only config[key] = value.

from collections import UserDict


class AuditedDict(dict[str, str]):
def __init__(self, *args: object, **kwargs: str) -> None:
super().__init__(*args, **kwargs) # type: ignore[arg-type]
self.log: list[str] = []

def __setitem__(self, key: str, value: str) -> None:
self.log.append(f"{key}={value}")
super().__setitem__(key, value)


cfg = AuditedDict()
cfg["tax_rate"] = "0.20"
cfg.update(tax_rate="0.25", bonus_cap="5000") # bypasses the override
print(cfg.log, dict(cfg))
# ['tax_rate=0.20'] {'tax_rate': '0.25', 'bonus_cap': '5000'}


class AuditedConfig(UserDict[str, str]):
def __init__(self, *args: object, **kwargs: str) -> None:
self.log: list[str] = [] # set before super().__init__, which calls __setitem__
super().__init__(*args, **kwargs) # type: ignore[arg-type]

def __setitem__(self, key: str, value: str) -> None:
self.log.append(f"{key}={value}")
super().__setitem__(key, value)


safe = AuditedConfig(region="EU")
safe["tax_rate"] = "0.20"
safe.update(tax_rate="0.25", bonus_cap="5000")
print(safe.log)
# ['region=EU', 'tax_rate=0.20', 'tax_rate=0.25', 'bonus_cap=5000']

Workflow Diagram:

dict subclass UserDict subclass
cfg["k"] = v ──▶ AuditedDict.__setitem__ ✓ safe["k"] = v ──▶ __setitem__ ✓
cfg.update(...) ──▶ C-level dict update ✗ safe.update(...) ──▶ MutableMapping.update
AuditedDict(...) ──▶ C-level dict init ✗ └──▶ __setitem__ ✓

Interviewer Notes:

  • The general lesson: inheriting from a concrete class makes you depend on its self-use (which of its methods call which). Prefer composition, or inherit from classes explicitly designed for extension (UserDict, UserList, collections.abc mixins).
  • The same issue exists with list subclasses (extend, slicing assignment) and str subclasses (methods return plain str).

Red Flags:

  • Overriding update too and assuming that covers everything (setdefault, |=, the constructor, copy() still behave differently).

Q46: Shipments are processed twice: an object's hash changed while it was inside a set​

Level: Senior

Scenario: A fulfilment worker keeps processed: set[Shipment] to avoid sending the same shipment to the carrier twice. Some customers receive two physical packages. The duplicates always involve shipments whose status changed while the worker was running.

Impact: Double shipping costs, inventory drift, and support tickets.

Root Cause: Shipment was declared @dataclass(unsafe_hash=True), so its hash is computed from all fields, including the mutable status. After shipment.status = "label_printed", the object sits in the set's bucket for its old hash. The membership test computes the new hash, looks in a different bucket, and returns False, so the shipment is treated as new.

Fix:

  1. Entities hash and compare by an immutable identity (shipment_id), never by mutable state.
  2. Better still, deduplicate on the ID itself (set[str]), which is also what you would store in Redis or a database for cross-process idempotency.
  3. Ban unsafe_hash=True on mutable classes in code review.
from dataclasses import dataclass, field


@dataclass(unsafe_hash=True) # hash uses ALL fields, including mutable status
class BuggyShipment:
shipment_id: str
status: str


s = BuggyShipment("SHP-1", "created")
processed = {s}
s.status = "label_printed" # hash changes while inside the set
print(s in processed) # False -> would be shipped again
print(len(processed), next(iter(processed)) is s) # 1 True - it IS there, just unreachable


@dataclass(eq=False)
class Shipment:
shipment_id: str
status: str = field(default="created")

def __eq__(self, other: object) -> bool:
if not isinstance(other, Shipment):
return NotImplemented
return self.shipment_id == other.shipment_id

def __hash__(self) -> int:
return hash(self.shipment_id)


ok = Shipment("SHP-1")
done = {ok}
ok.status = "label_printed"
print(ok in done) # True

# Preferred: dedupe on the identifier itself
processed_ids: set[str] = set()


def ship_once(shipment: Shipment) -> bool:
if shipment.shipment_id in processed_ids:
return False
processed_ids.add(shipment.shipment_id)
return True


print(ship_once(ok), ship_once(ok)) # True False

Workflow Diagram:

add(s) when status="created" hash(s) = H1 ──▶ bucket[H1] holds s
s.status = "label_printed" hash(s) = H2 (object not moved)
s in processed? look in bucket[H2] ──▶ empty ──▶ False
──▶ shipment sent to carrier again

Interviewer Notes:

  • This connects directly to the __eq__/__hash__ contract (Q25): a hash must not change for the lifetime of an object while it is stored in a hash-based container.
  • Principal angle: an in-memory set only deduplicates within one process. Real idempotency needs a durable unique constraint (for example a unique index on shipment_id in a carrier_requests table).

Red Flags:

  • "Remove and re-add the object to the set every time you mutate it."
  • Using a list instead of a set "because sets are buggy".

Q47: Random wrong query results after enabling Gunicorn --preload: a shared connection after fork()​

Level: Principal

Scenario: To speed up boot time, a team enabled Gunicorn's --preload, which imports the application in the master process before forking workers. The app module creates a module-level singleton db = Database(connect()) at import time. Shortly after deploy, a small percentage of requests return another request's rows or fail with protocol errors such as "unexpected message" or "lost synchronization with server".

Impact: Data correctness incident: some responses contained data belonging to other users.

Root Cause: fork() copies the parent's memory, including the open socket file descriptor. Every worker ended up sharing one TCP connection to the database. Concurrent queries from different workers interleave on the same socket, so replies are read by the wrong process. The singleton pattern hid the problem because "there is only one instance" was true per process image, not per OS process.

Fix:

  1. Never open sockets, connection pools, or threads at import time. Create them lazily, per process.
  2. Track the PID that created the resource and recreate it in a child process, or reset it in an os.register_at_fork(after_in_child=...) hook (or Gunicorn's post_fork server hook).
  3. For SQLAlchemy, its documentation describes disposing the engine's pool in the child (engine.dispose(close=False)) so the child does not reuse the parent's connections.
import os
from collections.abc import Callable


class Connection:
def __init__(self) -> None:
self.owner_pid = os.getpid()

def query(self, sql: str) -> str:
return f"pid={os.getpid()} ran {sql!r} on conn owned by {self.owner_pid}"


class PerProcess[T]:
"""Lazily creates one T per OS process; safe across fork()."""

def __init__(self, factory: Callable[[], T]) -> None:
self._factory = factory
self._value: T | None = None
self._pid: int | None = None
if hasattr(os, "register_at_fork"):
os.register_at_fork(after_in_child=self._reset)

def _reset(self) -> None:
self._value = None # do not close: the parent still owns that socket
self._pid = None

def get(self) -> T:
pid = os.getpid()
if self._value is None or self._pid != pid:
self._value = self._factory()
self._pid = pid
return self._value


db = PerProcess(Connection) # cheap at import time: no connection opened yet

print(db.get().query("SELECT 1"), flush=True) # flush before fork to avoid duplicated output

if hasattr(os, "fork"):
child = os.fork()
if child == 0: # child process
conn = db.get()
print("child uses its own connection:", conn.owner_pid == os.getpid(), flush=True)
os._exit(0)
os.waitpid(child, 0)

Workflow Diagram:

BEFORE (--preload + import-time connection)
master: import app ──▶ connect() ──▶ socket fd 7
│ fork() fork() fork()
▼ ▼ ▼
worker1 fd 7 worker2 fd 7 worker3 fd 7 ──▶ one DB session, interleaved replies

AFTER (lazy, per-process)
master: import app (no I/O) ──fork──▶ worker1: first request ──▶ own connection
──fork──▶ worker2: first request ──▶ own connection

Interviewer Notes:

  • The principal-level insight is that "singleton" and "global" have to be defined relative to a concurrency unit: process, thread, event loop, or request. Each needs a different holder (per-process lazy init, threading.local, per-loop clients, request-scoped DI).
  • The same bug class hits Celery prefork workers, multiprocessing, and any library that starts background threads at import time.

Red Flags:

  • "Add a lock around the connection" (locks are not shared across processes and do not fix shared socket state).
  • Closing the inherited connection in the child, which can send a termination message on the parent's live session.

Q48: Deploy fails with "partially initialized module": circular imports between domain modules​

Level: Senior

Scenario: A developer adds a Customer.outstanding_balance() method that calls billing code. Billing already imports Customer for type hints and to load customers. The service now crashes at startup with ImportError: cannot import name 'Customer' from partially initialized module 'customers' (most likely due to a circular import).

Impact: Failed deploy, and a team that starts adding imports inside functions everywhere to "make it work".

Root Cause: Two modules depend on each other at import time. When customers starts importing, it imports billing, which tries from customers import Customer before customers has finished executing, so the name does not exist yet. The import error is a symptom of a design cycle: two modules that each know about the other are effectively one module.

Fix:

  1. Decide the dependency direction. Domain models should not depend on services; services depend on models.
  2. If the model really needs a capability, have it depend on a small Protocol it owns (Dependency Inversion) and receive the implementation as an argument.
  3. For imports needed only for annotations, use if TYPE_CHECKING: so the import never runs at runtime.
  4. Add an import-linting check (for example the import-linter tool's layers contract) so the cycle cannot come back.
import importlib
import sys
import tempfile
import textwrap
from pathlib import Path

root = Path(tempfile.mkdtemp())
sys.path.insert(0, str(root))

# ---- The broken cycle ----
(root / "customers_bad.py").write_text(textwrap.dedent("""
from billing_bad import balance_for

class Customer:
def __init__(self, cid: int) -> None:
self.cid = cid

def outstanding_balance(self) -> int:
return balance_for(self)
"""))
(root / "billing_bad.py").write_text(textwrap.dedent("""
from customers_bad import Customer

def balance_for(customer: Customer) -> int:
return 100
"""))

try:
importlib.import_module("customers_bad")
except ImportError as exc:
print("ImportError:", str(exc).split(" (")[0])

# ---- The fix: one dependency direction + a Protocol owned by the model ----
(root / "customers_ok.py").write_text(textwrap.dedent("""
from typing import Protocol

class BalanceSource(Protocol):
def balance_for(self, customer_id: int) -> int: ...

class Customer:
def __init__(self, cid: int) -> None:
self.cid = cid

def outstanding_balance(self, source: BalanceSource) -> int:
return source.balance_for(self.cid)
"""))
(root / "billing_ok.py").write_text(textwrap.dedent("""
from customers_ok import Customer # billing -> customers only

class BillingService:
def balance_for(self, customer_id: int) -> int:
return 100

def statement(self, customer: Customer) -> str:
return f"customer {customer.cid} owes {self.balance_for(customer.cid)}"
"""))

customers = importlib.import_module("customers_ok")
billing = importlib.import_module("billing_ok")
c = customers.Customer(42)
print(c.outstanding_balance(billing.BillingService())) # 100
print(billing.BillingService().statement(c))

Workflow Diagram:

BEFORE (cycle) AFTER (acyclic)
customers ──imports──▶ billing billing ──imports──▶ customers
▲ │ │
└─────imports─────────┘ owns BalanceSource (Protocol)
BillingService satisfies it structurally

Interviewer Notes:

  • Strong answers treat the import error as an architecture signal rather than a Python quirk, and describe layering rules (for example api → services → domain, never upwards).
  • from __future__ import annotations or TYPE_CHECKING fixes annotation-only cycles, but not cycles where both modules call each other at runtime.

Red Flags:

  • Sprinkling function-local imports to dodge the error without addressing the dependency direction.
  • Merging everything into one large module.

Q49: Invoices with wrong totals: an anemic domain model lets services break invariants​

Level: Principal

Scenario: Order is a plain data bag with public items, discount_cents, and total_cents fields. Five different services (cart, promotions, admin tools, returns, and a migration script) modify orders directly. Finance discovers a few hundred invoices where total_cents does not match the line items: the returns service removes items but never recalculates the total.

Impact: Incorrect invoices and refunds, a manual reconciliation project, and an audit finding.

Root Cause: An anemic domain model: the object holding the data has no behavior, so the business rules ("total equals items minus discount", "discount cannot exceed subtotal", "cannot modify a paid order") are copied into every service. Any caller that forgets one rule creates invalid state. Storing a derived value (total_cents) that can drift from its source makes it worse.

Fix: Make Order an aggregate that guards its own invariants (Tell, Don't Ask):

  1. Keep items private; expose intention-revealing methods (add_item, remove_item, apply_discount, mark_paid).
  2. Compute totals from items instead of storing an independent copy (or recompute inside the aggregate on every change).
  3. Enforce lifecycle rules inside the aggregate (no edits after payment).
  4. Services orchestrate (load, call domain method, save); they do not contain business rules.
from dataclasses import dataclass


class OrderError(Exception):
pass


@dataclass(frozen=True)
class OrderLine:
sku: str
unit_cents: int
quantity: int

@property
def total_cents(self) -> int:
return self.unit_cents * self.quantity


class Order:
def __init__(self, order_id: str) -> None:
self.order_id = order_id
self._lines: dict[str, OrderLine] = {}
self._discount_cents = 0
self._paid = False

# --- queries ---
@property
def subtotal_cents(self) -> int:
return sum(line.total_cents for line in self._lines.values())

@property
def total_cents(self) -> int: # derived, so it cannot drift
return self.subtotal_cents - self._discount_cents

# --- commands that protect invariants ---
def add_item(self, sku: str, unit_cents: int, quantity: int) -> None:
self._ensure_editable()
if quantity <= 0 or unit_cents < 0:
raise OrderError("invalid line")
existing = self._lines.get(sku)
new_qty = quantity + (existing.quantity if existing else 0)
self._lines[sku] = OrderLine(sku, unit_cents, new_qty)

def remove_item(self, sku: str) -> None:
self._ensure_editable()
self._lines.pop(sku, None)
self._discount_cents = min(self._discount_cents, self.subtotal_cents)

def apply_discount(self, cents: int) -> None:
self._ensure_editable()
if not 0 <= cents <= self.subtotal_cents:
raise OrderError("discount must be between 0 and the subtotal")
self._discount_cents = cents

def mark_paid(self) -> None:
if not self._lines:
raise OrderError("cannot pay for an empty order")
self._paid = True

def _ensure_editable(self) -> None:
if self._paid:
raise OrderError("paid orders cannot be modified")


order = Order("ORD-1")
order.add_item("BOOK", 2_500, 2)
order.add_item("PEN", 300, 1)
order.apply_discount(1_000)
print(order.total_cents) # 4300
order.remove_item("BOOK") # discount is clamped; total stays consistent
print(order.total_cents) # 0
order.add_item("PEN", 300, 1)
order.mark_paid()
try:
order.add_item("PEN", 300, 1)
except OrderError as exc:
print(exc) # paid orders cannot be modified

Workflow Diagram:

BEFORE (anemic) AFTER (rich aggregate)
CartSvc ──┐ CartSvc ──┐
PromoSvc ─┼──▶ order.items / order.total PromoSvc ─┼──▶ order.add_item()
Returns ──┤ (each service re-implements Returns ──┤ order.apply_discount()
Admin ────┘ the rules, or forgets) Admin ────┘ order.remove_item()
│ invariants checked
▼ in ONE place
Repository.save(order)

Interviewer Notes:

  • The principal-level discussion includes migration: write a reconciliation query to find broken rows, route all writers through the aggregate (making fields private reveals every direct writer as a failing test or type error), then backfill.
  • Discuss the boundary: aggregates should be small enough to load and save as one unit inside one transaction.

Red Flags:

  • Adding a nightly job that "fixes" totals instead of preventing invalid state.
  • Validation only in the API layer while scripts and admin tools bypass it.

Q50: Order history page takes 6 seconds: a leaky repository returns lazy-loading ORM objects​

Level: Senior

Scenario: The order history endpoint was fast in development, but in production p95 latency is several seconds for long-standing customers. Database metrics show hundreds of tiny SELECT ... FROM order_lines WHERE order_id = ? queries per request.

Impact: Slow page loads, database CPU spikes, and connection pool exhaustion during peak hours, which slows unrelated endpoints too.

Root Cause: OrderRepository.list_for_customer() returns ORM entities with lazy-loaded relationships. The repository looks like an abstraction, but it leaks persistence behavior: the template iterates order.lines and each access silently fires a query (the N+1 problem). The caller cannot tell from the interface that attribute access does I/O. Lazy loading can also fail outright when the session has already closed.

Fix:

  1. Repositories return fully-loaded domain objects or read models (plain dataclasses), not ORM proxies.
  2. Load related rows in a constant number of queries: a JOIN, or a second query with WHERE order_id IN (...). (In SQLAlchemy this is eager loading such as selectinload; in Django prefetch_related.)
  3. Add a query-count assertion in tests for list endpoints so N+1 regressions fail CI.
import sqlite3
from collections import defaultdict
from dataclasses import dataclass

conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);
CREATE TABLE order_lines (order_id INTEGER, sku TEXT, qty INTEGER);
""")
for oid in range(1, 51):
conn.execute("INSERT INTO orders VALUES (?, 7)", (oid,))
conn.executemany("INSERT INTO order_lines VALUES (?, ?, ?)", [(oid, "A", 1), (oid, "B", 2)])

queries: list[str] = []
conn.set_trace_callback(queries.append) # records every SQL statement executed


# ---- Leaky version: attribute access performs I/O ----
class LazyOrder:
def __init__(self, conn: sqlite3.Connection, order_id: int) -> None:
self._conn, self.id = conn, order_id

@property
def lines(self) -> list[tuple[str, int]]:
return self._conn.execute(
"SELECT sku, qty FROM order_lines WHERE order_id = ?", (self.id,)
).fetchall()


def list_orders_lazy(customer_id: int) -> list[LazyOrder]:
rows = conn.execute("SELECT id FROM orders WHERE customer_id = ?", (customer_id,))
return [LazyOrder(conn, r[0]) for r in rows.fetchall()]


queries.clear()
items = sum(len(o.lines) for o in list_orders_lazy(7))
print("lazy:", items, "lines in", len(queries), "queries") # 100 lines in 51 queries


# ---- Fixed version: repository returns fully loaded read models ----
@dataclass(frozen=True)
class OrderLineView:
sku: str
qty: int


@dataclass(frozen=True)
class OrderView:
id: int
lines: tuple[OrderLineView, ...]


def list_orders_loaded(customer_id: int) -> list[OrderView]:
order_ids = [r[0] for r in conn.execute(
"SELECT id FROM orders WHERE customer_id = ? ORDER BY id", (customer_id,)
)]
if not order_ids:
return []
placeholders = ",".join("?" * len(order_ids))
lines: dict[int, list[OrderLineView]] = defaultdict(list)
for order_id, sku, qty in conn.execute(
f"SELECT order_id, sku, qty FROM order_lines WHERE order_id IN ({placeholders})",
order_ids, # values are bound parameters; only "?" markers are formatted in
):
lines[order_id].append(OrderLineView(sku, qty))
return [OrderView(oid, tuple(lines[oid])) for oid in order_ids]


queries.clear()
items = sum(len(o.lines) for o in list_orders_loaded(7))
print("loaded:", items, "lines in", len(queries), "queries") # 100 lines in 2 queries

Workflow Diagram:

BEFORE: 1 + N queries AFTER: 2 queries, regardless of N
SELECT orders ............ 1 SELECT orders ..................... 1
for order in orders: SELECT lines WHERE order_id IN (...) 1
order.lines ──▶ SELECT lines × N group lines by order_id in memory
return immutable OrderView objects

Interviewer Notes:

  • The OOP lesson is about honest abstractions: an interface that hides expensive behavior behind cheap-looking attribute access is leaky. Read models make the cost explicit at the repository boundary.
  • Very large IN lists have database-specific parameter limits; batch them or use a JOIN for big result sets, and paginate the endpoint.

Red Flags:

  • "Add a cache in front of the endpoint" without fixing the query pattern.
  • Building the IN (...) list by formatting the ID values directly into the SQL string.