Complete Technical Interview Questions & Answers
A comprehensive OneHub-style guide covering core fundamentals to advanced topics across backend, infrastructure, queues, serverless, ORM, and data science.
Table of Contents
- Core Fundamentals
- Python & FastAPI
- Framework Comparison (PHP & Laravel)
- Databases & Storage
- APIs & Protocols
- DevOps & Infrastructure
- FastAPI Deep Dive
- SQLAlchemy & ORM Patterns
- Realtime WebSockets & SSE
- Server-Sent Events (SSE)
- Laravel ORM (Eloquent)
- Alembic
- Password Hashing & Cryptography
- Data Structures & Algorithms
- Python 3.12-3.14 Features
- Design Patterns
- Testing
- Git & Version Control
- Python 3.13 - Free-Threading & JIT
- Context Managers & Iterators
- Data Science: Pandas, NumPy, Polars
Coverage Summary
| Area | Coverage |
|---|---|
| Total Questions | 3131+ |
| Core Fundamentals | Python, SQL, networking, Linux, HTTP, memory, concurrency |
| Advanced Backend | FastAPI, PostgreSQL, Redis, Django, Laravel, Git |
| Distributed Systems | K8s, queues, system design, serverless, ORM patterns |
| AI / Data | LangChain, RAG, NumPy, Pandas, Polars |
1. Core Fundamentals
Core Language Execution Models
Q1: What is the fundamental difference between Python and PHP execution?
-
A: PHP follows a shared-nothing architecture where each HTTP request:
- Initializes a new PHP process
- Loads the PHP interpreter and application code
- Executes the request-specific logic
- Returns the response
- Terminates the process, clearing all memory
This prevents memory leaks but means no state persists between requests without external storage (databases, Redis, sessions).
Python web frameworks (like FastAPI with Uvicorn/Gunicorn) use a persistent process model:
- Worker processes start when the application launches
- Each worker loads the application code once into memory
- Multiple requests are handled by the same worker process
- Application state (database connections, caches, loaded models) persists between requests
- Workers only terminate on shutdown or crash
Example:
// PHP - State does NOT persist between requests// File: counter.phpsession_start();if (!isset($_SESSION['count'])) {$_SESSION['count'] = 0;}$_SESSION['count']++;echo "Count: " . $_SESSION['count'];# Python/FastAPI - State CAN persist in memory between requests# File: main.pyfrom fastapi import FastAPIapp = FastAPI()# This variable persists in memory between requests!request_count = 0@app.get("/")def read_root():global request_countrequest_count += 1return {"message": f"Hello World, request #{request_count}"}
Q2: What is Dynamic Typing in Python?
-
A: In Python, variables don't have fixed types. You assign a value to a variable, and Python determines the type at runtime based on that value. You can reassign the same variable to different types during execution.
Example:
# Same variable holding different types at different timesx = 10 # x is an integerx = "hello" # x is now a stringx = [1, 2, 3] # x is now a listx = {"key": "value"} # x is now a dictionary# Type checking happens at runtimedef add_numbers(a, b):# This will work if a and b are numbers# But will fail with a TypeError if they're strings or other typesreturn a + badd_numbers(5, 3) # Returns 8add_numbers("5", "3") # Returns "53" (string concatenation)add_numbers(5, "3") # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'
Q3: Difference between a List and a Tuple?
-
A: Lists and Tuples are both sequence data types in Python that store collections of items, but they have key differences in mutability, performance, and use cases.
Feature List Tuple Mutability Mutable (can change) Immutable (cannot change) Syntax [1, 2, 3](1, 2, 3)Memory Larger (dynamic resizing) Smaller (fixed size) Performance Slower Faster Use Case Collections of items that change Constant data, dictionary keys Key Differences:
- Mutability: You can add, remove, or modify elements in a list. Once a tuple is created, you cannot change its contents.
- Memory: Lists require more memory because Python over-allocates space to allow for efficient appending (dynamic resizing). Tuples are fixed-size and more memory-efficient.
- Hashability: Tuples are "hashable" if all their elements are hashable, meaning they can be used as keys in a dictionary or elements in a set. Lists cannot.
Example:
# List examplemy_list = [1, 2, 3]my_list[0] = 10 # Works!my_list.append(4) # Works!# Tuple examplemy_tuple = (1, 2, 3)# my_tuple[0] = 10 # Raises TypeError# my_tuple.append(4) # Raises AttributeError# Tuple as dictionary keylocations = {(40.7128, -74.0060): "New York",(34.0522, -118.2437): "Los Angeles"}
Q4: What is a Dictionary?
-
A: A Dictionary in Python is an unordered (ordered since Python 3.7+) collection of data stored in
key: valuepairs. It uses a Hash Table internally to provide near-instant lookups (O(1) average time complexity).Characteristics:
- Unique Keys: Each key must be unique and hashable (like strings, numbers, or tuples).
- Mutable Values: Values can be any data type and can be changed.
- Fast Lookups: Finding a value by its key is extremely fast regardless of the dictionary size.
Example:
user = {"id": 1,"username": "krispdev","email": "krisp@example.com","is_active": True}# Accessing dataprint(user["username"]) # "krispdev"# Adding/Updatinguser["last_login"] = "2026-03-20"# Safe access with .get()role = user.get("role", "guest") # Returns "guest" if key doesn't exist
Q5: What is a Set?
-
A: A Set is an unordered collection of unique elements. It is essentially a dictionary where you only care about the keys and not the values.
Characteristics:
- Uniqueness: Automatically removes duplicates.
- Unordered: Items have no defined order (you cannot index them like
my_set[0]). - Fast Membership Testing: Checking if an item exists (
if item in my_set) is O(1) average time complexity.
Example:
numbers = {1, 2, 3, 3, 2, 1, 4}print(numbers) # {1, 2, 3, 4} (duplicates removed)# Useful for set operationsset_a = {1, 2, 3}set_b = {3, 4, 5}print(set_a | set_b) # Union: {1, 2, 3, 4, 5}print(set_a & set_b) # Intersection: {3}print(set_a - set_b) # Difference: {1, 2}
Q6: How does if __name__ == "__main__": work?
-
A: This idiom allows a Python file to be run either as a standalone script or as a module imported into another script.
How it works:
- Every Python file has a built-in variable called
__name__. - When you run a file directly (e.g.,
python script.py), Python sets__name__to"__main__". - When you import a file into another one, Python sets
__name__to the filename (e.g.,"script").
Purpose: It prevents code from executing automatically when a file is imported. This is where you put setup code, tests, or the main entry point of your program.
Example:
# File: my_module.pydef calculate_sum(a, b):return a + b# This only runs if you do: python my_module.py# It will NOT run if you do: import my_moduleif __name__ == "__main__":print("Running module directly...")result = calculate_sum(10, 20)print(f"Result: {result}") - Every Python file has a built-in variable called
Q7: What are List Comprehensions?
-
A: List comprehensions provide a concise way to create lists based on existing iterables. They are often more readable and slightly faster than using traditional
forloops with.append().Syntax:
[expression for item in iterable if condition]Example:
# Traditional waysquares = []for x in range(10):if x % 2 == 0:squares.append(x**2)# List comprehension waysquares = [x**2 for x in range(10) if x % 2 == 0]# Result: [0, 4, 16, 36, 64]
Q8: Difference between == and is?
-
A: These operators check for different types of equality.
==checks for Equality of Value: Do these two variables hold the same data?ischecks for Equality of Identity: Do these two variables point to the exact same memory address?
Example:
a = [1, 2, 3]b = [1, 2, 3]c = aprint(a == b) # True (Values are the same)print(a is b) # False (Different objects in memory)print(a is c) # True (Point to the same object)Note: Python "interns" some small integers and strings, so
x is ymight be True for small numbers even if they were created separately, but you should never rely on this behavior.
Q9: What is a Namespace?
-
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's like a dictionary where keys are the variable names and values are the objects themselves.
Types of Namespaces (LEGB Rule):
- Local: Inside a function.
- Enclosing: Inside nested functions (parent function's scope).
- Global: At the top level of a module/file.
- Built-in: Names pre-defined by Python (like
len,print).
Example:
x = "global" # Global namespacedef outer():x = "enclosing" # Enclosing namespacedef inner():x = "local" # Local namespaceprint(x)inner()outer()
Q10: What is a Decorator?
-
A: A decorator is a function that takes another function as an argument and extends its behavior without explicitly modifying it. It's a way to "wrap" code.
Common Uses: Logging, authentication, timing functions, caching.
Example:
def my_logger(func):def wrapper(*args, **kwargs):print(f"Calling function: {func.__name__}")result = func(*args, **kwargs)print(f"Finished {func.__name__}")return resultreturn wrapper@my_loggerdef say_hello(name):print(f"Hello, {name}!")say_hello("John")# Output:# Calling function: say_hello# Hello, John!# Finished say_hello
Q11: How does PHP run differently from Python?
- A: PHP is designed to "die" after every request. It starts fresh, runs your code, and then clears everything from memory. Python apps usually stay "alive" in the background between requests.
Q12: What is an Interface in PHP?
- A: It's a contract that says "any class that uses this must have these specific functions." It ensures different classes can be used interchangeably.
Q13: Compare String Concatenation in Python vs PHP
- A: PHP uses a dot to join text. Python uses a plus sign. PHP's way is slightly safer because it won't accidentally try to add a number to a string and crash.
Q14: What are Closures and the use keyword in PHP?
- A: In PHP, if you write a function inside another function, you have to explicitly list which outside variables it's allowed to see. Python just lets it see them automatically.
Q15: What is a Trait in PHP vs Multiple Inheritance in Python?
- A: PHP uses "Traits" to share code between classes without making the family tree too complicated. Python allows a class to have multiple "parents" directly, and it has a specific set of rules to decide which parent's code to run first if there's a conflict.
2. Python & FastAPI
Python Concurrency & Async I/O
Q16: What is Concurrency?
-
A: Concurrency is the ability of a program to handle multiple tasks at the same time. It doesn't necessarily mean the tasks are running simultaneously (that's parallelism); rather, it means the tasks are making progress in overlapping time periods.
Key Concepts:
- Context Switching: The process of storing the state of a task so it can be resumed later, allowing another task to run.
- I/O Bound: Tasks that spend most of their time waiting for external resources (network, disk). Concurrency is very effective here.
- CPU Bound: Tasks that spend most of their time performing calculations. Parallelism (multiprocessing) is needed here.
Q17: Difference between a Thread and a Process?
-
A:
- Process: An independent instance of a running program. It has its own dedicated memory space, stack, and resources. Processes are isolated from each other.
- Thread: The smallest unit of execution within a process. Multiple threads can exist within a single process and share the same memory space.
Feature Process Thread Memory Own memory space (isolated) Shared memory space Overhead High (slower to create/switch) Low (faster to create/switch) Communication Difficult (IPC: Pipes, Sockets) Easy (Shared variables) Failure One crash doesn't affect others One crash can kill the whole process GIL Impact Bypasses GIL (in Python) Limited by GIL (in Python)
Q18: What is AsyncIO?
-
A:
asynciois a Python library used to write concurrent code using theasync/awaitsyntax. It uses a single-threaded, single-process event loop to handle many tasks by "yielding" control when a task is waiting for I/O.How it works: Instead of having many workers (threads) waiting around, you have one worker that checks a list of tasks. When a task hits an
await(like a database query), the worker moves to the next task. When the query finishes, the first task is moved back to the "ready" list to be finished.Example:
import asyncioasync def fetch_data(id):print(f"Task {id} starting...")await asyncio.sleep(2) # Simulating I/O (network call)print(f"Task {id} finished!")return f"Data {id}"async def main():# Run 3 tasks concurrentlyresults = await asyncio.gather(fetch_data(1), fetch_data(2), fetch_data(3))print(results)asyncio.run(main())
Q19: When should you use Multiprocessing instead of Threading?
-
A:
- Use Multiprocessing for CPU-bound tasks (heavy calculations, image processing, data science). Since each process has its own Python interpreter and memory, it bypasses the GIL and can use all CPU cores in parallel.
- Use Threading (or AsyncIO) for I/O-bound tasks (web scraping, API calls, database queries). These tasks spend most of their time waiting, so sharing one CPU core while juggling tasks is more efficient than the overhead of creating new processes.
Rule of Thumb:
- Need more "Brains" (CPU)? -> Multiprocessing.
- Need more "Waiters" (I/O)? -> Threading/AsyncIO.
Q20: What is a Race Condition?
-
A: A race condition occurs when two or more threads/processes access shared data and try to change it at the same time. The final result depends on the unpredictable timing of their execution (who "wins the race").
Example:
import threadingcounter = 0def increment():global counterfor _ in range(100000):counter += 1 # This is NOT atomic!t1 = threading.Thread(target=increment)t2 = threading.Thread(target=increment)t1.start(); t2.start()t1.join(); t2.join()print(counter) # Often less than 200,000!
Q21: How do Locks prevent Race Conditions?
-
A: A Lock (or Mutex) is a synchronization primitive that ensures only one thread can access a shared resource at a time. If a thread wants to use the resource, it must first "acquire" the lock. If another thread already holds it, the requesting thread must wait.
Fixed Example with Lock:
import threadingcounter = 0lock = threading.Lock()def increment():global counterfor _ in range(100000):with lock: # Only one thread can enter this block at a timecounter += 1t1 = threading.Thread(target=increment)t2 = threading.Thread(target=increment)t1.start(); t2.start()t1.join(); t2.join()print(counter) # Guaranteed to be 200,000
Advanced Python Internals
Q22: How does Python's Garbage Collection work?
-
A: Python uses reference counting as its primary garbage collection mechanism, supplemented by a generational cycle detector to handle reference cycles.
Reference Counting:
- Each Python object maintains a reference count (refcount) that tracks how many references point to it.
- When you assign an object to a variable, pass it to a function, or store it in a container, the refcount increases.
- When a reference is deleted (variable reassigned, goes out of scope, or container item removed), the refcount decreases.
- When an object's refcount reaches zero, it is immediately deallocated and its memory is returned to the Python heap.
Example:
import sysa = [] # refcount of new list = 1b = a # refcount becomes 2c = a # refcount becomes 3del b # refcount becomes 2c = None # refcount becomes 1a = [1, 2, 3] # original list refcount becomes 0 -> immediately deallocatedLimitations of Reference Counting:
-
Cannot handle reference cycles (circular references) where objects reference each other but are no longer reachable from the root set.
-
Example:
class Node:def __init__(self):self.child = Noneself.parent = Noneparent = Node()child = Node()parent.child = childchild.parent = parent # Creates a cycledel parent, child # Variables gone, but objects still reference each other -> refcounts never reach zero
Generational Cycle Detector:
- Python's garbage collector runs periodically to find and break reference cycles.
- It uses generational hypothesis: younger objects are more likely to become garbage.
- Objects are divided into three generations (0, 1, 2). New objects start in generation 0.
- When generation 0 exceeds a threshold, a partial collection runs. If many objects survive, they get promoted to older generations.
- The collector traverses objects, identifies cycles, and breaks them by decrefing references.
You can interact with the GC via the
gcmodule:import gc# Disable automatic garbage collectiongc.disable()# Manually trigger collectioncollected = gc.collect() # Returns number of objects collected# Set thresholds for generations (threshold0, threshold1, threshold2)gc.set_threshold(700, 10, 10) # Default valuesPerformance Considerations:
- Reference counting is fast and deterministic for most objects.
- Cycle detection pauses the program; frequency depends on object allocation patterns.
- For applications creating many short-lived objects, tuning GC thresholds can improve throughput.
- In multi-threaded programs, the GIL protects reference count updates, making them thread-safe but potentially a bottleneck.
Q23: What is a Generator?
-
A: A generator is a special type of iterator in Python that yields values one at a time using the
yieldkeyword. Unlike lists, generators do not store all values in memory at once; they generate values on-the-fly.Benefits:
- Memory Efficiency: Ideal for processing massive datasets (gigabytes of logs, millions of database rows) that wouldn't fit in RAM.
- Lazy Evaluation: Computations only happen when you ask for the next value.
Example:
# Memory-heavy waydef get_squares_list(n):return [x**2 for x in range(n)] # Creates the whole list in memory# Memory-efficient way (Generator)def get_squares_gen(n):for x in range(n):yield x**2 # Returns one at a time, pauses state# Usagegen = get_squares_gen(1000000)print(next(gen)) # 0print(next(gen)) # 1
Q24: Explain *args and **kwargs.
-
A: These are special syntaxes for passing a variable number of arguments to a function.
*args(Non-Keyword Arguments): Collects extra positional arguments into a tuple.**kwargs(Keyword Arguments): Collects extra named arguments into a dictionary.
Example:
def multi_purpose_func(required, *args, **kwargs):print(f"Required: {required}")print(f"Extra positional: {args}")print(f"Extra named: {kwargs}")multi_purpose_func("test", 1, 2, 3, mode="debug", user="admin")# Output:# Required: test# Extra positional: (1, 2, 3)# Extra named: {'mode': 'debug', 'user': 'admin'}
Q25: What is Scope (LEGB rule)?
- A: Scope defines the visibility and lifetime of variables. Python follows the LEGB rule to look up names:
- L (Local): Names assigned within a function (and not declared global).
- E (Enclosing): Names in the local scope of any and all enclosing functions (nested functions).
- G (Global): Names assigned at the top-level of a module file, or declared global in a def.
- B (Built-in): Names preassigned in the built-in names module (e.g.,
open,range,ValueError).
Q26: What is a Context Manager (with statement)?
-
A: A context manager is an object that defines the runtime context to be established when executing a
withstatement. It handles the setup and teardown logic (e.g., opening and closing resources) automatically.How it works:
- It uses
__enter__()to set up the resource. - It uses
__exit__()to clean up the resource, even if an error occurs.
Example:
# Built-in context manager for fileswith open("data.txt", "w") as f:f.write("Hello")# File is automatically closed here!# Custom context manager using a classclass DatabaseConnection:def __enter__(self):print("Connecting to DB...")return selfdef __exit__(self, exc_type, exc_val, exc_tb):print("Closing connection...")with DatabaseConnection() as db:print("Doing work...") - It uses
Q27: What is the Global Interpreter Lock (GIL)?
-
A: The GIL is a mutex (lock) that allows only one thread to hold control of the Python interpreter at a time. This means even on multi-core systems, only one thread can execute Python bytecode at any given moment.
Why does it exist?
- It makes memory management (reference counting) thread-safe and simple to implement in CPython.
- It makes integrating C libraries (which are often not thread-safe) much easier.
Impact:
- I/O Bound tasks: Minimal impact. Threads can release the GIL while waiting for I/O (network, disk).
- CPU Bound tasks: Significant impact. Multi-threaded Python is slower than single-threaded for heavy math because of lock contention. Use
multiprocessingto bypass it.
Q28: How are Python Dictionaries so fast?
-
A: Python dictionaries use a Hash Table implementation.
- When you use a key, Python runs it through a
hash()function to get an integer. - This integer is used to calculate an index in an underlying array.
- Python stores the
(hash, key, value)triplet at that index.
This allows for O(1) constant time lookups on average. In recent Python versions (3.6+), dictionaries are also more memory-efficient and maintain insertion order by using a compact array of indices pointing to a larger array of entries.
- When you use a key, Python runs it through a
Q29: What are __slots__?
-
A: By default, Python instances use a dictionary (
__dict__) to store their attributes. This is flexible but consumes a lot of memory.__slots__allows you to explicitly declare which attributes an instance can have.Benefits:
- Memory Savings: Can reduce memory usage by 40-50% for classes with many instances.
- Faster Attribute Access: Slightly faster because it uses a fixed-size array instead of a hash table lookup.
Example:
class Point:__slots__ = ('x', 'y') # No __dict__ createddef __init__(self, x, y):self.x = xself.y = y
Q30: What is a Metaclass?
-
A: A metaclass is a class that creates other classes. In Python, "everything is an object," and classes are objects too. Just as a class defines the behavior of an instance, a metaclass defines the behavior of a class.
Use Cases:
- Automatically adding methods to classes.
- Registering classes at creation time (e.g., for plugins or ORMs).
- Enforcing coding standards or API constraints across many classes.
Example:
class Singleton(type):_instances = {}def __call__(cls, *args, **kwargs):if cls not in cls._instances:cls._instances[cls] = super().__call__(*args, **kwargs)return cls._instances[cls]class Database(metaclass=Singleton):pass
Q31: How does the Method Resolution Order (MRO) work?
-
A: MRO is the order in which Python searches for a method or attribute in a class hierarchy, especially important in multiple inheritance.
Algorithm: Python uses the C3 Linearization algorithm.
- It maintains a monotonic property (parents always come after children).
- It follows the order defined in the class base list (left-to-right).
You can check a class's MRO using
ClassName.mro()orClassName.__mro__.Example:
class A: passclass B(A): passclass C(A): passclass D(B, C): passprint(D.mro())# Output: [D, B, C, A, object]
Q32: Explain the Event Loop in AsyncIO.
- A: It's a non-stop loop that checks a "to-do list." If a task is waiting for something (like a website to respond), the loop moves it to a "waiting" pile and starts the next task. As soon as the website responds, the loop moves that task back to the "ready" pile.
Q33: What are Task Groups (Python 3.11+)?
- A: It's a way to launch a bunch of tasks together and wait for all of them to finish. If even one task fails, the group automatically stops all the others so you don't leave "ghost" tasks running in the background.
Q34: How do Context Variables work in async code?
- A: Normally, global variables are shared by everyone. Context Variables are "smart": they look like global variables, but they keep different values for every different task, so Task A doesn't accidentally see Task B's data.
Q35: What is yield from in generators?
- A: It creates a direct "pipe" between a main generator and a sub-generator. It allows the main one to pass all values and errors directly through to the sub-one without having to write a manual loop to handle every single item.
Q36: What does yield do?
- A: It pauses a function and gives a value back, but keeps the function's state so it can continue later. It's like taking a break mid-task and coming back to finish.
Q37: What is a Coroutine?
- A: It's a special type of function that can pause and resume. Unlike regular functions that run from start to finish, coroutines can "yield" control to let other tasks run.
Q38: What is the difference between await and yield?
- A:
awaittells Python to wait for another coroutine to finish before continuing.yieldpauses the function and gives control back to whoever called it.
Q39: What is asyncio.gather?
- A: It launches multiple coroutines at once and waits for all of them to finish. It's like starting several tasks simultaneously and waiting for all to complete.
Q40: What is asyncio.create_task?
- A: It schedules a coroutine to run in the background. It returns immediately without waiting for the task to finish.
3. Framework Comparison (PHP & Laravel)
PHP Core Concepts
Q41: What are PHP Attributes vs Python Decorators?
- A: A Python decorator is a wrapper that actually changes how a function behaves as soon as the code starts. A PHP Attribute is just a label or a note attached to a piece of code. It doesn't do anything by itself; you have to write separate code that looks for those labels and decides what to do based on them.
Q42: PHP's __call vs Python's __call__?
- A: In Python,
__call__lets you treat an object (like a "User" object) as if it were a function you can run. In PHP,__callis a fallback method: if you try to run a function on an object that doesn't exist, PHP runs__callinstead so you can handle the mistake or redirect it.
Q43: PHP Array vs Python List/Dict
- A: PHP uses one "Array" type for everything—whether it's a simple list or a set of key-value pairs. Python splits these into "Lists" (for ordered items) and "Dictionaries" (for key-value pairs).
Q44: PHP Namespaces vs Python Modules
- A: PHP namespaces are just labels used to organize code; you have to tell PHP where the actual files are. Python modules are directly tied to the files on your computer—one file is automatically one module.
Q45: What is PHP's JIT Compiler?
- A: It stands for "Just In Time." It takes parts of your code that run over and over and turns them into raw machine instructions that the computer can run directly, which can make heavy calculations much faster.
Q46: What is Constructor Property Promotion in PHP 8?
- A: It's a shortcut in PHP 8 that lets you define and set up class variables all in one line at the top of the class, instead of writing them out multiple times.
Q47: What is the Nullsafe Operator (?->)?
- A: It's a safety tool. If you try to get data from something that might be missing (null), this operator will just return "null" instead of crashing your whole app.
Q48: What are PHP Match Expressions vs switch?
- A: "Match" is a newer, stricter way to check a variable against many options. Unlike the old
switch, it returns a value directly and doesn't have "fallthrough" bugs where it accidentally runs the wrong code.
Q49: What are Named Arguments in PHP?
- A: This lets you pass data to a function by using the names of the arguments (like
name: 'John') instead of just the order. This makes your code much easier to read and allows you to skip optional parts easily.
Q50: What is a Readonly Class in PHP?
- A: It's a class where every single piece of data inside it can only be set once and never changed again. This makes the code safer and easier to predict.
Laravel Framework Internals
Q51: What is Laravel's Service Container?
-
A: The Service Container is a powerful tool for managing class dependencies and performing dependency injection. It is the "heart" of Laravel.
Core Functions:
- Dependency Injection: Automatically injecting class dependencies through the constructor.
- Binding: Registering how an interface should be resolved to a concrete class.
- Resolution: Extracting a class instance from the container.
Example:
// 1. Binding an interface to an implementation$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);// 2. Dependency Injection in a controllerclass OrderController extends Controller {public function __construct(protected PaymentGateway $gateway) {}public function checkout() {// $this->gateway is automatically an instance of StripePaymentGateway$this->gateway->charge(100);}}
Q52: What are Laravel Facades?
-
A: Facades provide a "static" interface to classes that are available in the application's service container. They serve as "proxy" objects to the underlying implementation.
How it works: When you call
Cache::get('key'), Laravel resolves thecacheservice from the container and calls thegetmethod on that instance.Example:
// Using a Facade (looks static but isn't)use Illuminate\Support\Facades\Cache;Cache::put('key', 'value', 600);// Equivalent to manual resolutionapp('cache')->put('key', 'value', 600);
Q53: What is Laravel's Eloquent ORM?
-
A: Eloquent is an Implementation of the Active Record pattern. Each database table has a corresponding "Model" used to interact with that table.
Key Features:
- Relationships: Define One-to-One, One-to-Many, Many-to-Many using methods.
- Accessors/Mutators: Transform data when reading or writing.
- Scopes: Encapsulate common query logic.
Example:
// Fetching data$user = User::where('active', 1)->first();// Creating dataUser::create(['name' => 'John', 'email' => 'john@example.com']);// Defining a relationship in User modelpublic function posts() {return $this->hasMany(Post::class);}
Q54: What are Laravel Middleware?
-
A: Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. They act as "layers" around your application logic.
Common Uses:
- Authentication (
authmiddleware) - CSRF Protection
- Logging
- Rate Limiting
Example:
public function handle(Request $request, Closure $next): Response {// 1. Logic BEFORE the request is handledif ($request->input('token') !== 'secret') {return redirect('home');}$response = $next($request);// 2. Logic AFTER the request is handledreturn $response;} - Authentication (
Q55: What is Laravel's Blade templating?
-
A: Blade is a powerful templating engine that allows you to write plain PHP in your templates without the messy syntax. Unlike other engines, Blade compiles into plain PHP code and caches it for performance.
Features:
- Template Inheritance:
@extends,@section,@yield. - Control Structures:
@if,@foreach,@auth. - Components: Reusable UI pieces.
Example:
{{-- layout.blade.php --}}<html><body>@yield('content')</body></html>{{-- home.blade.php --}}@extends('layout')@section('content')<h1>Welcome, {{ $user->name }}</h1>@foreach($posts as $post)<p>{{ $post->title }}</p>@endforeach@endsection - Template Inheritance:
Q56: What are Laravel Queues?
-
A: Queues allow you to defer the processing of a time-consuming task, such as sending an email or processing an image, until a later time. This drastically speeds up web requests to your application.
Workflow:
- Application dispatches a "Job" to a queue (Redis, Database, Amazon SQS).
- A background "Worker" process polls the queue and executes the job.
Example:
// Dispatching a jobProcessPodcast::dispatch($podcast);// Command to start a worker// php artisan queue:work
Q57: What is Laravel's Event System?
-
A: Laravel's events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. It helps in decoupling logic.
Components:
- Event: A class representing the action (e.g.,
OrderShipped). - Listener: A class that handles the action (e.g.,
SendShipmentNotification).
Example:
// Dispatching an eventOrderShipped::dispatch($order);// In EventServiceProviderprotected $listen = [OrderShipped::class => [SendShipmentNotification::class,UpdateInventory::class,],]; - Event: A class representing the action (e.g.,
Q58: What are Laravel Migrations?
-
A: Migrations are like version control for your database, allowing your team to define and share the application's database schema definition.
Commands:
php artisan make:migration create_users_tablephp artisan migrate(Apply changes)php artisan migrate:rollback(Undo changes)
Example:
public function up(): void {Schema::create('flights', function (Blueprint $table) {$table->id();$table->string('name');$table->timestamps();});}
Q59: What is Laravel's Route Model Binding?
-
A: This feature automatically injects the model instance that has an ID matching the corresponding segment in the request URI.
Example:
// RouteRoute::get('/users/{user}', function (User $user) {return $user->email;});// If user visits /users/1, Laravel automatically finds User with ID 1// and passes it to the closure. If not found, it returns a 404.
Q60: What are Laravel Policies?
-
A: Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a
Postmodel and a correspondingPostPolicy.Example:
class PostPolicy {public function update(User $user, Post $post): bool {return $user->id === $post->user_id;}}// In Controller$this->authorize('update', $post);
4. Databases & Storage
SQL Fundamentals & Relational Theory
Q61: What is a Primary Key?
- A: It's a unique ID for each row in a table. No two rows can have the same primary key, and it can't be empty.
Q62: What is a Foreign Key?
- A: It's a column that links to a primary key in another table. It creates a relationship between two tables.
Q63: What is Indexing?
- A: It's like the index at the back of a book. It helps the database find data faster without scanning every single row.
Q64: What is a JOIN?
- A: It's a way to combine data from two or more tables based on related columns.
Q65: What is the difference between INNER JOIN and LEFT JOIN?
- A: INNER JOIN only shows rows that have matches in both tables. LEFT JOIN shows all rows from the left table and matching rows from the right (or empty if no match).
Q66: What is Normalization?
- A: It's the process of organizing data to reduce redundancy. It splits large tables into smaller, related tables.
Q67: What is Denormalization?
- A: It's the opposite of normalization - intentionally adding duplicate data to make reads faster.
Q68: What are ACID properties?
- A: Atomicity (all or nothing), Consistency (valid data), Isolation (concurrent changes don't interfere), Durability (saved even if system crashes).
Q69: What is a Transaction?
- A: It's a group of operations that either all succeed or all fail. If any part fails, everything is rolled back.
Q70: What is Database Locking?
- A: It's a mechanism that prevents two people from changing the same data at the same time.
Q71: What is a Deadlock?
- A: It's when two transactions are waiting for each other to release locks, creating a cycle where neither can proceed.
Q72: What is Query Optimization?
- A: It's making your database queries run faster by rewriting them, adding indexes, or changing the database structure.
Q73: What is Connection Pooling?
- A: It's keeping a pool of open database connections so new requests can reuse them instead of creating new connections each time.
Q74: What is Database Replication?
- A: It's copying data from one database to another for backup or to share the load of reading data.
Q75: What is Database Sharding?
- A: It's splitting data across multiple databases to handle very large amounts of data.
PostgreSQL Deep Dive
Q76: What is PostgreSQL?
- A: It's a powerful, open-source relational database known for reliability and advanced features.
Q77: What are PostgreSQL JSON columns?
- A: They let you store JSON data in a column, giving you flexibility to store semi-structured data.
Q78: What are PostgreSQL Window Functions?
- A: They let you perform calculations across related rows without grouping them, useful for rankings and running totals.
Q79: What is PostgreSQL CTE (Common Table Expression)?
- A: It's a temporary named result set that you can reference within a query, making complex queries easier to read.
Q80: What is PostgreSQLVACUUM?
- A: It's a process that reclaims storage space and updates statistics after rows are deleted or updated.
Redis Internals & Patterns
Q81: What is Redis?
- A: It's an in-memory data store commonly used for caching and real-time features.
Q82: Redis Data Types
- A: Strings, Lists, Sets, Sorted Sets, Hashes, Bitmaps, HyperLogLogs, Geospatial indexes.
Q83: What is Redis Pub/Sub?
- A: It's a messaging system where publishers send messages to channels, and subscribers receive messages from those channels.
Q84: What is Redis Persistence?
- A: Redis can save data to disk using RDB (snapshots) or AOF (every command), providing durability options.
5. APIs & Protocols
REST APIs & HTTP Semantics
Q85: What is a REST API?
- A: It's a way for applications to talk to each other using standard web methods (GET, POST, PUT, DELETE). Think of it like ordering from a menu - you know what to expect.
Q86: What is the difference between GET and POST?
- A: GET requests data (like reading a page). POST sends data to be processed (like submitting a form).
Q87: What is JSON?
- A: JavaScript Object Notation - a simple text format for sending data, easy for humans to read and machines to parse.
Q88: What is API Authentication?
- A: It's verifying who is making the request. Common methods include API keys, tokens (JWT), and OAuth.
Q89: What is JWT?
- A: JSON Web Token - a compact way to securely transmit information between parties as a JSON object.
Q90: What is Rate Limiting?
- A: It's restricting how many requests a user can make in a certain time period to prevent abuse.
Q91: What is API Versioning?
- A: It's a way to make changes to your API without breaking existing clients. You can have /v1/users and /v2/users.
Q92: What is HATEOAS?
- A: Hypermedia as the Engine of Application State - a principle where responses include links to related actions.
Q93: What is OpenAPI/Swagger?
- A: It's a standard for describing REST APIs so both humans and machines can understand them.
Microservices & Distributed Patterns
Q94: What are Microservices?
- A: An architecture style where an application is built as a collection of small, independent services, each doing one thing well.
Q95: What is Service Discovery?
- A: It's how services find each other in a distributed system, like a phone book for your services.
Q96: What is API Gateway?
- A: A single entry point for all clients that routes requests to the right service and handles cross-cutting concerns.
Q97: What is Circuit Breaker?
- A: A pattern that prevents cascading failures by stopping calls to a failing service temporarily.
Q98: What is Distributed Tracing?
- A: It's tracking a request as it moves through multiple services to help debug issues.
Q99: What is Event-Driven Architecture?
- A: Services communicate by sending and receiving events (messages) rather than direct calls.
Q100: What is CQRS?
- A: Command Query Responsibility Segregation - separating read and write operations into different models for better performance.
Q101: What is API Profiling and why do we need it?
-
A: API profiling is measuring and analyzing how long different parts of your API take to execute. It tracks timing data for database queries, external API calls, function execution, and response generation.
What it captures:
- Total request time (how long the user waits)
- Database query time (how long SQL takes)
- External service calls (payment gateways, email services)
- Function-level timing (which code is slow)
- Memory usage during request
Why we need it:
- Find bottlenecks: Identify which database query or function is making users wait
- Optimize performance: Focus improvement efforts on the slowest parts
- Detect regressions: Catch performance drops before deploying to production
- Capacity planning: Understand resource usage under different loads
- Debug slow requests: See exactly where time is spent when a user complains about slowness
Example with cProfile (Python):
import cProfileimport pstatsdef my_slow_endpoint():profiler = cProfile.Profile()profiler.enable()# Your API logic hereresult = fetch_user_data()process_payments()profiler.disable()stats = pstats.Stats(profiler)stats.sort_stats('cumtime').print_stats(10) # Top 10 slowest callsreturn result
6. DevOps & Infrastructure
System Design & Scalability
Q102: What is Load Balancing?
-
A: A load balancer is a traffic manager that sits between users and your servers. When many users visit your website, the load balancer receives all their requests first, then forwards each request to an available server. This prevents any single server from getting too busy and ensures all servers share the work evenly.
How it works:
- User sends a request to your website
- Load balancer receives the request
- Load balancer picks a server based on its algorithm
- Server processes the request and sends response back through load balancer
- User receives the response
Benefits:
- No single server becomes a bottleneck
- If one server fails, traffic automatically goes to healthy servers
- You can add or remove servers without users noticing
Q103: What is Round Robin Algorithm?
-
A: The simplest way to distribute traffic. The load balancer maintains a list of servers and sends each new request to the next server in line, looping back to the first after reaching the last.
Example with 3 servers:
- Request 1 → Server A
- Request 2 → Server B
- Request 3 → Server C
- Request 4 → Server A (loops back)
Best for: When all servers have similar power and requests take roughly the same time to process.
Q104: What is Least Connections Algorithm?
-
A: The load balancer tracks how many active connections each server currently has, and sends new requests to the server with the fewest active connections.
How it works:
- Server A has 50 active users → busy
- Server B has 10 active users → less busy
- Server C has 25 active users → moderately busy
- New request goes to Server B
Best for: When requests take different amounts of time (some are quick, some are slow). Prevents slow requests from piling up on one server.
Q105: What is IP Hash Algorithm?
-
A: The load balancer uses a mathematical function on the user's IP address to always send the same user to the same server. This is also called "sticky sessions."
How it works:
- User with IP 192.168.1.5 always goes to Server A
- User with IP 192.168.1.10 always goes to Server B
- Same user returning will hit the same server
Best for: When you need to maintain user session data on a specific server and cannot share sessions between servers.
Downside: If that server fails, those users lose their session until the server recovers.
Q106: What is Weighted Round Robin?
-
A: Similar to Round Robin, but some servers get more requests than others based on their capacity. You assign a "weight" to each server.
Example:
- Server A (powerful): weight = 3 → gets 3 requests
- Server B (medium): weight = 2 → gets 2 requests
- Server C (weak): weight = 1 → gets 1 request
- Pattern repeats: A, A, A, B, B, C, A, A, A, B, B, C...
Best for: When your servers have different hardware specs. Powerful servers handle more traffic.
Q107: What is Weighted Least Connections?
-
A: Combines Least Connections with server weights. The load balancer considers both the current number of connections AND the server's capacity when deciding where to send traffic.
How it works:
- Server A (weight 3): 30 connections → ratio = 10 connections per weight unit
- Server B (weight 2): 20 connections → ratio = 10 connections per weight unit
- Server C (weight 1): 5 connections → ratio = 5 connections per weight unit
- New request goes to Server C (lowest ratio)
Best for: Mixed environment where servers have different power AND requests vary in processing time.
Q108: What is Horizontal vs Vertical Scaling?
- A: Vertical: adding more power to existing machines. Horizontal: adding more machines.
Q109: What is Caching?
- A: Storing frequently accessed data in fast storage so you don't have to fetch it from the source every time.
Q110: What is CDN?
- A: Content Delivery Network - servers placed around the world to deliver content faster to users based on their location.
Q111: What is Message Queue?
- A: A way for services to communicate asynchronously. One service sends a message that another service picks up later.
Q112: What is Docker?
- A: A platform for packaging applications in containers - self-contained packages that include everything needed to run.
Q113: What is Kubernetes?
- A: A system for automating deployment, scaling, and management of containerized applications.
Q114: What is CI/CD?
- A: Continuous Integration (merging code frequently) and Continuous Deployment (automatically deploying changes).
Q115: What is Monitoring?
- A: Tracking application health and performance using logs, metrics, and alerts.
Q116: What is Logging?
- A: Recording events and errors so you can debug issues and understand what's happening.
Q117: What is Prometheus and what does it do?
-
A: Prometheus is a monitoring system that collects and stores metrics from your applications and servers. It pulls data at regular intervals and stores it as time-series data (values with timestamps).
What it does:
- Scrapes metrics from applications (CPU, memory, request counts, response times)
- Stores data locally in a time-series database
- Lets you query data using PromQL (Prometheus Query Language)
- Sends alerts when thresholds are breached
Use cases:
- Monitor server health (CPU, disk, memory usage)
- Track application performance (request rates, error rates, latency)
- Alert when services go down or performance degrades
Example metric:
http_requests_total{method="GET", endpoint="/api/users"} 150
Q118: What is Grafana and how is it different from Prometheus?
-
A: Grafana is a visualization tool that creates dashboards and graphs from data sources like Prometheus. While Prometheus collects and stores metrics, Grafana displays them in readable charts.
Key differences:
Feature Prometheus Grafana Role Data collection & storage Data visualization Primary job Scrapes metrics, sends alerts Creates dashboards & charts Data source Its own time-series DB Connects to multiple sources Query language PromQL Uses source's query language Use cases:
- Build real-time dashboards showing system health
- Create alerts based on visual thresholds
- Combine data from multiple sources (Prometheus, CloudWatch, Elasticsearch)
- Share performance reports with teams
How they work together: Prometheus collects metrics → Grafana queries Prometheus → Grafana displays graphs
Q119: What is SigNoz and how is it different from Prometheus/Grafana?
-
A: SigNoz is an all-in-one observability platform that combines metrics, logs, and traces in a single tool. Unlike Prometheus (metrics only) + Grafana (visualization only), SigNoz provides complete observability out of the box.
Key differences:
Feature Prometheus + Grafana SigNoz Scope Metrics only Metrics + Logs + Traces Setup Install two tools + configure Single installation Correlations Manual between tools Automatic correlations Traces Not supported Built-in distributed tracing Use cases:
- Full observability without managing multiple tools
- Distributed tracing to track requests across microservices
- Correlate metrics spikes with specific log entries
- Open-source alternative to Datadog/New Relic
Best for: Teams wanting unified observability without enterprise tool costs.
Q120: What is OpenTelemetry and how does it relate to these tools?
-
A: OpenTelemetry is a standard for collecting telemetry data (metrics, logs, traces) from applications. It's not a monitoring tool itself—it's a common language that applications use to export data to tools like Prometheus, Grafana, or SigNoz.
What it does:
- Provides libraries to instrument application code
- Standardizes how data is collected and formatted
- Exports data to any compatible backend (Prometheus, SigNoz, Jaeger, etc.)
Analogy:
- OpenTelemetry = USB standard (common interface)
- Prometheus/SigNoz = Hard drive (stores the data)
- Grafana = Monitor (displays the data)
Use cases:
- Avoid vendor lock-in (switch backends without changing code)
- Standardize observability across multiple programming languages
- Collect traces, metrics, and logs with one library
Example workflow:
Your App (with OpenTelemetry) → Exports data → SigNoz/Prometheus/Grafana
Q121: What is Backpressure and how do you solve it?
-
A: Backpressure happens when a fast producer overwhelms a slow consumer. Like a water pipe where too much water flows in faster than it can drain out - eventually the pipe bursts.
Common scenarios:
- API receives requests faster than it can process them
- Queue producer adds messages faster than consumers can remove them
- Database writes come in faster than disk can handle
Solutions:
- Rate limiting: Slow down the producer (reject or delay excess requests)
- Buffering/Queueing: Add a queue between producer and consumer to absorb spikes
- Load shedding: Drop excess requests gracefully when overloaded
- Auto-scaling: Add more consumers when queue grows too large
- Circuit breaker: Stop accepting requests when system is at capacity
Example with queue:
# Instead of direct processing, add to bounded queueif queue.full():return "Server busy, try again later" # Backpressurequeue.put(request)
Q122: What is the Thundering Herd Problem?
-
A: When many processes or requests simultaneously try to access the same resource after it becomes available. Like hundreds of people rushing through a single door when it opens.
How it happens:
- A resource (cache entry, database connection) expires or becomes unavailable
- Many waiting requests all try to access it at the same time
- System gets overwhelmed trying to serve all requests simultaneously
Solutions:
- Request coalescing: Only let one request through to rebuild cache, others wait
- Staggered retry: Add random delays so not all retries happen at once
- Circuit breaker: Block requests temporarily until system recovers
- Warm cache: Pre-populate cache before expiry to prevent gaps
Example - Cache warming:
# Instead of letting all requests hit database when cache expires:if cache_expired and not rebuilding:rebuilding = True # Only one request rebuildscache = rebuild_cache() # Others wait or use stale data temporarily
Q123: What is Cache Stampede?
-
A: A specific type of thundering herd that happens with cached data. When a popular cache entry expires, many requests simultaneously try to regenerate it, overloading the database.
Difference from Thundering Herd:
- Thundering herd: general resource access pattern
- Cache stampede: specific to cache expiry scenarios
Solutions:
- Lock-based: Only one process regenerates cache while others wait or use stale data
- Early expiry: Refresh cache before it actually expires (stale-while-revalidate)
- Probabilistic early expiry: Randomly expire some nodes early to spread load
- External recomputation: Background job refreshes cache, not user requests
Example - Stale-while-revalidate:
# Serve stale data while refreshing in backgroundif cache_expired:async_refresh_cache() # Don't block userreturn cached_data # Return slightly old data
Q124: What is the N+1 Query Problem?
-
A: A performance issue where you make one query to get N items, then make N additional queries to get related data for each item. Total queries: N+1 instead of 1 or 2.
Example of the problem:
# BAD: N+1 queriesusers = db.query("SELECT * FROM users") # 1 queryfor user in users:orders = db.query(f"SELECT * FROM orders WHERE user_id={user.id}") # N queries# Total: 101 queries for 100 usersSolutions:
- Eager loading (JOIN): Fetch all data in one query
# GOOD: Single query with JOINusers_with_orders = db.query("""SELECT * FROM usersJOIN orders ON users.id = orders.user_id""")
- Batch loading: Fetch related data for all items at once
# GOOD: 2 queries totalusers = db.query("SELECT * FROM users") # 1 queryuser_ids = [u.id for u in users]orders = db.query(f"SELECT * FROM orders WHERE user_id IN {user_ids}") # 1 query
- DataLoader pattern: Batch and cache related queries automatically
- GraphQL field-level batching: Use DataLoader to batch similar requests
- Eager loading (JOIN): Fetch all data in one query
7. FastAPI Deep Dive
FastAPI Basics & ASGI Flow
Q125: What is FastAPI?
-
A: FastAPI is a modern, high-performance web framework for building APIs with Python 3.8+ based on standard Python type hints.
Key Advantages:
- Performance: As fast as NodeJS and Go, thanks to Starlette (web features) and Pydantic (data features).
- Fast Coding: Increases development speed by 200% to 300%.
- Automatic Docs: Generates interactive API documentation (Swagger UI and ReDoc) automatically.
- Type Safety: Uses Python type hints for data validation, serialization, and editor support (autocompletion).
- Asynchronous: Built-in support for
async/await.
Q126: How is FastAPI different from Flask or Django?
- A:
- vs Flask: Flask is a micro-framework that is synchronous by default and requires third-party libraries for validation (Marshmallow) and docs (Flasgger). FastAPI has these built-in and is natively asynchronous.
- vs Django: Django is "batteries-included" (ORM, Admin, Auth all included). FastAPI is focused specifically on APIs, giving you more flexibility to choose your own database, ORM, and auth tools, while being significantly faster.
Q127: How do you create a basic FastAPI endpoint?
-
A:
from fastapi import FastAPIapp = FastAPI()@app.get("/items/{item_id}")async def read_item(item_id: int, q: str = None):return {"item_id": item_id, "query": q}What happens here?
item_idis captured as an integer (automatic conversion).qis an optional query parameter.- FastAPI automatically validates that
item_idis a number. - Returns a JSON response automatically.
Q128: What are Path Parameters vs Query Parameters?
- A:
- Path Parameters: Part of the URL path. Used to identify a specific resource.
- Example:
/users/{user_id}->/users/42
- Example:
- Query Parameters: Set of key-value pairs that appear after the
?in the URL. Used for filtering, sorting, or pagination.- Example:
/users?role=admin&limit=10
- Example:
- Path Parameters: Part of the URL path. Used to identify a specific resource.
Q129: What is Pydantic in FastAPI?
-
A: Pydantic is the data validation library that FastAPI uses. You define "Models" as Python classes, and Pydantic ensures the data entering or leaving your API matches those models.
Example:
from pydantic import BaseModel, EmailStrclass UserCreate(BaseModel):username: stremail: EmailStr # Validates email formatage: int | None = None # Optional
Q130: How does FastAPI handle Request Bodies?
-
A: You use Pydantic models as function parameters. FastAPI reads the JSON body from the request, validates it against the model, and passes it to your function as an object.
Example:
@app.post("/users/")async def create_user(user: UserCreate):# 'user' is already a validated object herereturn {"message": f"User {user.username} created"}If the client sends invalid JSON (e.g., a string for
age), FastAPI automatically returns a422 Unprocessable Entityerror with details.
Q131: How does FastAPI handle request bodies?
- A: You use Pydantic models to define what data you expect. FastAPI automatically validates and converts the JSON to a Python object.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_available: bool = True
@app.post("/items/")
def create_item(item: Item):
return item
Q132: What is FastAPI Dependency Injection?
- A: It's a way to automatically provide resources (like database connections) to your functions. Instead of creating them inside each function, you declare what you need, and FastAPI provides it.
from fastapi import Depends
def get_database():
db = connect_to_db()
try:
yield db
finally:
db.close()
@app.get("/users/")
def get_users(db = Depends(get_database)):
return db.query("SELECT * FROM users")
Q133: How do you return files in FastAPI?
- A: Use
FileResponseorStreamingResponsefor sending files back to the user.
from fastapi.responses import FileResponse
@app.get("/download/")
def download_file():
return FileResponse("myfile.txt", filename="download.txt")
Q134: How do you handle errors in FastAPI?
- A: Use
HTTPExceptionto return error responses.
from fastapi import HTTPException
@app.get("/users/{user_id}")
def get_user(user_id: int):
user = find_user(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
FastAPI Advanced Internals
Q135: What are FastAPI Background Tasks?
-
A: Background tasks allow you to schedule a function to run after the HTTP response has been sent to the client. This is ideal for tasks that don't need the user to wait, such as sending email notifications, logging analytics, or triggering webhooks.
Example:
from fastapi import BackgroundTasksdef write_log(message: str):with open("log.txt", "a") as f:f.write(message)@app.post("/send-notification/")async def send_notification(email: str, bt: BackgroundTasks):# 1. Schedule the taskbt.add_task(write_log, f"Notification sent to {email}")# 2. Return response immediatelyreturn {"message": "Task scheduled in background"}
Q136: What is FastAPI Middleware?
-
A: Middleware is a function that runs before every request is processed by a specific path operation, and after every response is generated.
Common Uses:
- Adding custom headers (e.g.,
X-Process-Time). - Request logging.
- CORS (Cross-Origin Resource Sharing) configuration.
- Trusted Host validation.
Example:
@app.middleware("http")async def add_process_time_header(request: Request, call_next):start_time = time.time()response = await call_next(request)process_time = time.time() - start_timeresponse.headers["X-Process-Time"] = str(process_time)return response - Adding custom headers (e.g.,
Q137: How do you secure FastAPI endpoints?
-
A: FastAPI provides the
fastapi.securitymodule which simplifies implementing authentication and authorization.Common Patterns:
- OAuth2 with Password flow: For login and getting tokens (JWT).
- API Keys: Simple header or query parameter validation.
- HTTP Basic/Bearer: Standard authentication headers.
Example (Bearer Token with Dependency Injection):
from fastapi.security import OAuth2PasswordBeareroauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")@app.get("/items/")async def read_items(token: str = Depends(oauth2_scheme)):# Only reachable if 'Authorization: Bearer <token>' header is presentreturn {"token": token}
Q138: What is FastAPI Lifespan?
-
A: Lifespan events are functions that run when the application starts up and when it shuts down. It's the modern replacement for
@app.on_event("startup").Use Case: Setting up database connection pools, loading ML models, or initializing shared caches.
Example:
from contextlib import asynccontextmanager@asynccontextmanagerasync def lifespan(app: FastAPI):# 1. Startup: Run this when the app startsawait database.connect()print("DB Connected")yield # The app runs here# 2. Shutdown: Run this when the app stopsawait database.disconnect()print("DB Disconnected")app = FastAPI(lifespan=lifespan)
Q139: How do you do WebSocket in FastAPI?
- A:
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
Q140: How does FastAPI generate documentation?
- A: FastAPI automatically generates OpenAPI documentation. Access it at
/docs(Swagger UI) or/redoc(ReDoc).
8. SQLAlchemy & ORM Patterns
SQLAlchemy Basics & Session Model
Q141: What is SQLAlchemy?
- A: SQLAlchemy is a Python tool that lets you work with databases using Python objects instead of writing SQL directly. It's like a translator between your Python code and the database.
Q142: What is the difference between Core and ORM?
- A: Core is the底层 (low-level) part - you write SQL-like statements. ORM (Object Relational Mapping) lets you use Python classes as database tables.
Q143: How do you create a table in SQLAlchemy?
- A:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
engine = create_engine('sqlite:///my.db')
Base.metadata.create_all(engine)
Q144: What is a Session in SQLAlchemy?
- A: A Session is like a conversation with the database. You use it to add, query, and update records.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
# Add a user
new_user = User(name="John", email="john@example.com")
session.add(new_user)
session.commit()
Q145: How do you query data in SQLAlchemy?
- A:
# Get one
user = session.query(User).filter(User.id == 1).first()
# Get all
users = session.query(User).all()
# Filter
users = session.query(User).filter(User.name.like('%John%')).all()
Q146: What is SQLAlchemy Relationship?
- A: It connects tables together. For example, a User can have many Posts.
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
posts = relationship("Post", back_populates="author")
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
author = relationship("User", back_populates="posts")
Q147: How do you update data in SQLAlchemy?
- A:
user = session.query(User).filter(User.id == 1).first()
user.name = "Jane"
session.commit()
Q148: How do you delete data in SQLAlchemy?
- A:
user = session.query(User).filter(User.id == 1).first()
session.delete(user)
session.commit()
Q149: What are SQLAlchemy Migrations?
- A: They track changes to your database structure over time. Use Alembic (which comes with SQLAlchemy) to create and apply migrations.
SQLAlchemy Advanced Patterns
Q150: What is SQLAlchemy Query Building?
- A: Building SQL queries using Python code instead of writing raw SQL.
from sqlalchemy import select
query = select(User).where(User.name == "John")
result = session.execute(query)
Q151: What is SQLAlchemy Joins?
- A:
from sqlalchemy import join
query = select(User).join(Post).where(Post.title.like('%Hello%'))
Q152: What is SQLAlchemy Subqueries?
- A: A query inside another query.
from sqlalchemy import func
subquery = session.query(func.count(Post.id)).filter(Post.user_id == User.id).scalar()
query = session.query(User, subquery.label('post_count'))
Q153: What is SQLAlchemy Events?
- A: Code that runs automatically when certain things happen, like before inserting or updating a record.
from sqlalchemy import event
@event.listens_for(User, "before_insert")
def receive_before_insert(mapper, connection, target):
target.created_at = datetime.now()
Q154: How do you do raw SQL in SQLAlchemy?
- A:
result = session.execute(text("SELECT * FROM users WHERE name = :name"), {"name": "John"})
Q155: What is SQLAlchemy Pooling?
- A: It keeps database connections open and reuses them instead of creating new ones for each request. This makes your app faster.
from sqlalchemy import create_engine
engine = create_engine('sqlite:///my.db', pool_size=10, max_overflow=20)
9. Realtime WebSockets & SSE
WebSocket Basics & Realtime Protocols
Q156: What is WebSocket?
- A: WebSocket is a way for a browser and server to keep an open connection. Unlike regular HTTP where the browser asks and server answers, WebSocket lets them talk back and forth anytime.
Q157: How is WebSocket different from HTTP?
- A: HTTP: Browser asks, server answers, connection closes. WebSocket: Connection stays open, both sides can send messages anytime. It's like a phone call vs sending letters.
Q158: What is a WebSocket handshake?
- A: It's the initial connection setup. The browser sends a special HTTP request asking to upgrade to WebSocket. If the server agrees, the connection stays open.
Q159: What are WebSocket frames?
- A: Messages are broken into frames. Each frame has information about whether it's text, binary, or the last frame of a message.
Q160: What is WebSocket ping/pong?
- A: They keep the connection alive. The server periodically sends a "ping", and the browser replies with "pong". If there's no response, the connection is closed.
Q161: How do you close a WebSocket connection?
- A: Either side can send a close frame with a code and reason. Codes like 1000 mean normal close, 1001 means one side is leaving.
WebSocket Implementation Patterns
Q162: How do you implement WebSocket in Python?
- A:
import asyncio
import websockets
async def chat(websocket, path):
async for message in websocket:
await websocket.send(f"Echo: {message}")
asyncio.get_event_loop().run_until_complete(
websockets.serve(chat, "localhost", 8765)
)
Q163: How do you implement WebSocket in JavaScript?
- A:
const ws = new WebSocket("ws://localhost:8765");
ws.onopen = () => console.log("Connected");
ws.onmessage = (event) => console.log("Message:", event.data);
ws.send("Hello");
ws.close();
Q164: What is WebSocket reconnection?
- A: When the connection drops, the client should automatically try to reconnect. Most libraries handle this with exponential backoff (wait longer each time).
Q165: What are WebSocket security concerns?
- A:
- Use wss:// (WebSocket Secure) instead of ws://
- Validate all incoming messages
- Implement rate limiting
- Use authentication tokens during handshake
10. Server-Sent Events (SSE)
Server-Sent Events Basics
Q166: What is Server-Sent Events?
- A: SSE is a way for a server to push updates to a browser automatically. The browser opens a connection, and the server sends data whenever it wants. One-way only - server to browser.
Q167: How is SSE different from WebSocket?
- A: WebSocket: Two-way communication, browser and server can both send. SSE: One-way, only server sends to browser. SSE is simpler and works better with regular HTTP.
Q168: What is SSE use case?
- A: Live feeds, notifications, stock prices, news updates, progress bars. Any situation where the server needs to push updates to the browser.
Q169: How do you implement SSE in Python?
- A:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import time
app = FastAPI()
def event_stream():
for i in range(10):
yield f"data: Message {i}\n\n"
time.sleep(1)
@app.get("/events")
def events():
return StreamingResponse(event_stream(), media_type="text/event-stream")
Q170: How do you implement SSE in JavaScript?
- A:
const source = new EventSource("/events");
source.onmessage = (event) => {
console.log("Message:", event.data);
};
source.onerror = (error) => {
console.log("Error:", error);
};
Q171: What is SSE reconnection?
- A: If the connection drops, the browser automatically tries to reconnect. The server can send a special "id" field, and the browser will send it back on reconnect so you know where to continue.
Q172: What is SSE heartbeat?
- A: Servers should periodically send comments (starting with :) to keep proxies and browsers from closing the connection due to inactivity.
11. Laravel ORM (Eloquent)
Eloquent Basics & Active Record
Q173: What is Laravel Eloquent?
- A: Eloquent is Laravel's ORM (Object Relational Mapper). It lets you work with database tables using Python-like objects instead of writing SQL.
Q174: How do you create an Eloquent model?
- A:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $fillable = ['name', 'email'];
}
Q175: How do you create records in Eloquent?
- A:
// Create
$user = User::create([
'name' => 'John',
'email' => 'john@example.com'
]);
// Or
$user = new User();
$user->name = 'John';
$user->save();
Q176: How do you query data in Eloquent?
- A:
// Get all
$users = User::all();
// Get one
$user = User::find(1);
// Filter
$users = User::where('name', 'John')->get();
Q177: What are Eloquent Relationships?
- A: They connect database tables. Types:
- One to One
- One to Many
- Many to Many
- Has One Through
- Has Many Through
Q178: How do you define One to Many in Eloquent?
- A:
// User has many Posts
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post belongs to User
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Q179: How do you update records in Eloquent?
- A:
$user = User::find(1);
$user->name = 'Jane';
$user->save();
Q180: How do you delete records in Eloquent?
- A:
$user = User::find(1);
$user->delete();
// Or
User::destroy(1);
Q181: What are Eloquent Accessors?
- A: They modify data when you read it from the database.
class User extends Model
{
public function getNameAttribute($value)
{
return ucfirst($value);
}
}
Q182: What are Eloquent Mutators?
- A: They modify data before saving to the database.
class User extends Model
{
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
}
Eloquent Advanced Optimization
Q183: What are Eloquent Scopes?
- A: Reusable query logic.
class User extends Model
{
public function scopeActive($query)
{
return $query->where('status', 'active');
}
}
// Usage
$activeUsers = User::active()->get();
Q184: What is Eloquent Pagination?
- A:
$users = User::paginate(15);
// Returns with links in view: {{ $users->links() }}
Q185: What are Eloquent Events?
- A: Code that runs when certain things happen.
class User extends Model
{
protected static function booted()
{
static::created(function ($user) {
// Do something after created
});
}
}
Q186: What is Eloquent Mass Assignment?
- A: Using
create()orupdate()with arrays. Use$fillableto allow certain fields, or$guardedto block certain fields.
class User extends Model
{
protected $fillable = ['name', 'email']; // These can be mass assigned
// OR
protected $guarded = ['id', 'password']; // These cannot
}
Q187: What are Eloquent Collections?
- A: Results from queries are wrapped in collections with helpful methods.
$users = User::all();
$names = $users->pluck('name');
$admins = $users->filter(fn($u) => $u->is_admin);
Q188: What is Eloquent Query Builder integration?
- A: You can mix Eloquent with raw SQL.
$users = User::whereRaw('price > ?', [100])->get();
12. Alembic
Alembic Basics & Schema Versioning
Q189: What is Alembic?
- A: Alembic is a database migration tool for SQLAlchemy. It tracks changes to your database structure (like adding columns) and applies them safely.
Q190: How do you create a migration in Alembic?
- A:
alembic revision --autogenerate -m "create users table"
Then edit the upgrade() and downgrade() functions.
Q191: How do you apply migrations?
- A:
# Apply all pending migrations
alembic upgrade head
# Apply one specific migration
alembic upgrade +1
# Go back one
alembic downgrade -1
Q192: How do you create a table in Alembic?
- A:
def upgrade():
op.create_table(
'users',
Column('id', Integer, primary_key=True),
Column('name', String(50)),
Column('email', String(100), unique=True)
)
def downgrade():
op.drop_table('users')
Q193: How do you add a column in Alembic?
- A:
def upgrade():
op.add_column('users', Column('age', Integer))
def downgrade():
op.drop_column('users', 'age')
Q194: What is Alembic autogenerate?
- A: It compares your SQLAlchemy models to the current database and automatically creates the migration to make them match.
alembic revision --autogenerate -m "add age column"
Q195: How do you check migration status?
- A:
alembic current
alembic history --verbose
Q196: What is Alembic downgrade?
- A: Rolling back migrations to undo changes.
alembic downgrade -1 # Go back one
alembic downgrade base # Go back to start
Alembic Advanced Migration Strategies
Q197: How do you handle data migrations?
- A:
def upgrade():
# Add new column
op.add_column('users', Column('new_status', String(20)))
# Migrate data
op.execute("UPDATE users SET new_status = 'active' WHERE status = 1")
# Drop old column
op.drop_column('users', 'status')
Q198: What are Alembic environments?
- A: Alembic can connect to different databases (dev, test, prod) using different configuration sections in alembic.ini.
Q199: What is Alembic context?
- A: The context provides database connection and metadata. You can customize it in env.py to include your SQLAlchemy models.
def run_migrations_offline():
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata
)
Q200: How do you seed data in Alembic?
- A: Migrations are for structure, not data. For data seeding, create a separate seed script or add data migration at the end.
def upgrade():
op.execute("INSERT INTO roles (name) VALUES ('admin'), ('user')")
13. Password Hashing & Cryptography
Basic Level
Q201: What is Password Hashing?
Answer: Password hashing is the process of converting a plain-text password into a fixed-length string of characters that cannot be easily reversed. When a user creates an account, you hash their password and store the hash, not the actual password. When they login, you hash the input and compare hashes.
Why use hashing?
- If your database is stolen, attackers can't see actual passwords
- Even if two users have the same password, hashes will be different (with salt)
- One-way function - can't reverse to get original password
Q202: What is the difference between Encryption and Hashing?
Answer:
| Aspect | Hashing | Encryption |
|---|---|---|
| Purpose | One-way, can't reverse | Two-way, can decrypt |
| Output Length | Fixed length | Variable length |
| Use Case | Passwords, checksums | Sensitive data, SSL |
| Reversible | No | Yes (with key) |
| Speed | Slower (intentional) | Faster |
Think of it like:
- Hashing: Burning a document - you can't unburn it
- Encryption: Putting a document in a safe - you can open it with a key
Q203: What is Salt in password hashing?
Answer: A salt is a random string added to each password before hashing. It ensures that even if two users have the same password, their hashes will be different.
import bcrypt
# Without salt - same password = same hash
hash1 = bcrypt.hashpw(b'password', bcrypt.gensalt())
hash2 = bcrypt.hashpw(b'password', bcrypt.gensalt()) # Different!
# With proper salt, each hash is unique
Why salt?
- Prevents rainbow table attacks
- Makes it harder to crack multiple passwords at once
- Each password needs individual cracking effort
Q204: What is bcrypt?
Answer: bcrypt is a password hashing function designed to be slow and memory-hard. It's based on the Blowfish cipher and includes built-in salting.
Key features:
- Automatically generates and stores salt
- Configurable work factor (cost)
- Adaptive - can increase cost as computers get faster
import bcrypt
# Hashing a password
password = b"my_secure_password"
hashed = bcrypt.hashpw(password, bcrypt.gensalt(rounds=12))
# Verifying a password
bcrypt.checkpw(password, hashed) # Returns True/False
Q205: What is Argon2?
Answer: Argon2 is the winner of the Password Hashing Competition (2015). It's designed to be resistant against GPU and ASIC attacks.
Three variants:
- Argon2d: Best for cryptocurrencies
- Argon2i: Best for password hashing
- Argon2id: Hybrid (default recommended)
# Using argon2
from argon2 import PasswordHasher
ph = PasswordHasher(
time_cost=2,
memory_cost=65536,
parallelism=1
)
# Hash
hash = ph.hash("password")
# Verify
ph.verify(hash, "password")
Q206: Why is bcrypt considered secure?
Answer: bcrypt is considered secure because:
- Slow by design - Includes a cost factor that makes it intentionally slow
- Built-in salt - Each password gets unique salt
- Proven track record - Been around since 1999
- Adaptive - Can increase work factor as hardware improves
- Battle-tested - Used by many companies for years
The key is the "work factor" (rounds):
- Higher rounds = slower but more secure
- Default is usually 10-12
- Can increase as computers get faster
Q207: What is a Rainbow Table attack?
Answer: A rainbow table is a pre-computed table of password hashes used to crack passwords. Attackers compute hashes for millions of common passwords once, then look up stolen hashes.
Defense:
- Use unique salt per password (bcrypt does this)
- Use slow hashing algorithms (bcrypt, Argon2)
- Use long passwords
# Without salt - vulnerable to rainbow table
import hashlib
hashlib.md5("password").hexdigest() # Same every time!
# With salt - protected
import bcrypt
bcrypt.hashpw(b"password", bcrypt.gensalt()) # Different each time!
Q208: What is the work factor in bcrypt?
Answer: The work factor (cost) in bcrypt determines how many iterations the algorithm runs. It's a power of 2.
# Cost of 10 = 2^10 = 1,024 iterations
# Cost of 12 = 2^12 = 4,096 iterations
# Cost of 14 = 2^14 = 16,384 iterations
hashed = bcrypt.hashpw(password, bcrypt.gensalt(rounds=12))
Trade-off:
- Higher cost = more secure but slower
- Lower cost = faster but less secure
- Recommendation: Start with 10-12, increase over time
Intermediate Level
Q209: What is the difference between bcrypt and Argon2?
Answer:
| Feature | bcrypt | Argon2 |
|---|---|---|
| Memory usage | Low (~4KB) | High (configurable) |
| GPU resistance | Moderate | Excellent |
| Side-channel resistance | Good | Excellent |
| Winner | Password Hashing Competition | Winner (2015) |
| Flexibility | Cost factor only | Time, memory, parallelism |
| Modern recommendation | Good | Better |
When to use bcrypt:
- Legacy systems
- When memory is constrained
- When Argon2 not available
When to use Argon2:
- New projects
- Maximum security needed
- When memory is available
Q210: What is PBKDF2?
Answer: PBKDF2 (Password-Based Key Derivation Function 2) is another secure hashing algorithm. It's widely used and part of many standards.
import hashlib
# PBKDF2 with SHA-256
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode(),
salt,
100000 # iterations
)
Features:
- Configurable iterations
- Can use different hash functions
- NIST recommended
- Good for key derivation but slower than bcrypt for passwords
Q211: What is scrypt?
Answer: scrypt is a password-based key derivation function that uses memory hardness. It's designed to be ASIC-resistant.
import hashlib
# scrypt
key = hashlib.scrypt(
password.encode(),
salt=salt,
n=16384, # CPU/memory cost
r=8, # Block size
p=1, # Parallelization
maxmem=0 # Memory limit
)
Features:
- Memory-hard - requires large memory
- Good for password hashing
- More resistant to GPU attacks
Q212: What is MD5 and why shouldn't it be used for passwords?
Answer: MD5 is a hash function but it's broken for security purposes:
Problems:
- Extremely fast (millions of hashes per second)
- No built-in salt
- Known collision vulnerabilities
- Rainbow tables widely available
# NEVER use for passwords!
import hashlib
hashlib.md5("password").hexdigest() # 5f4dcc3b5aa765d61d8327deb882cf99
Use bcrypt, Argon2, or PBKDF2 instead.
Q213: What is SHA-256 for passwords?
Answer: SHA-256 is better than MD5 but still not ideal for passwords:
Problems:
- Too fast - can compute billions per second
- No built-in salt (need to add manually)
- Designed for speed, not password hashing
# Better than MD5 but NOT for passwords
import hashlib
hashlib.sha256("password").hexdigest()
For passwords, use bcrypt, Argon2, or PBKDF2.
Q214: What is Password-Based Key Derivation Function (PBKDF)?
Answer: A PBKDF is specifically designed for password hashing. It applies a hash function multiple times to slow down attackers.
Key components:
- Password
- Salt (random data)
- Iteration count (work factor)
- Output length
The idea: Make hashing slow enough to be inconvenient for attackers but fast enough for legitimate users.
# PBKDF2 example
derived_key = PBKDF2(
password,
salt,
iterations=100000,
hashfunc=SHA256
)
Q215: How do you implement secure password storage?
Answer: Best practices for password storage:
- Use strong algorithm - bcrypt, Argon2id, or scrypt
- Use unique salt - bcrypt/Argon2 do this automatically
- Set appropriate work factor - balance security vs performance
- Use HTTPS - passwords shouldn't travel in plain text
- Implement rate limiting - prevent brute force attacks
- Use account lockout - after failed attempts
- Consider 2FA - additional security layer
# Good password storage in Python
import bcrypt
def hash_password(password):
return bcrypt.hashpw(
password.encode(),
bcrypt.gensalt(rounds=12)
)
def verify_password(password, hashed):
return bcrypt.checkpw(
password.encode(),
hashed
)
Advanced Level
Q216: What is Argon2id?
Answer: Argon2id is the recommended variant of Argon2. It combines Argon2d and Argon2i.
How it works:
- First third of memory uses Argon2d (data-dependent)
- Last two-thirds uses Argon2i (data-independent)
- Provides both GPU resistance and side-channel resistance
from argon2 import PasswordHasher
ph = PasswordHasher(
time_cost=2, # Number of passes
memory_cost=65536, # Memory in KB (64MB)
parallelism=1, # Parallel threads
hash_len=32, # Output length
salt_len=16 # Salt length
)
# Hash
hash = ph.hash("my_password")
# Verify
ph.verify(hash, "my_password")
Q217: What is memory-hard hashing?
Answer: Memory-hard hashing requires a large amount of memory to compute. This makes it resistant to GPU/ASIC attacks because these devices have limited memory.
Why important:
- GPUs can parallelize computations easily
- But can't access large amounts of memory quickly
- Memory-hard functions slow down both GPUs and ASICs
Argon2 and scrypt are memory-hard. bcrypt is not.
Q218: What is a timing attack?
Answer: A timing attack measures how long operations take to extract information. For password comparison, if you use regular string comparison, an attacker can measure response times to guess characters.
# VULNERABLE - stops at first wrong character
if password == stored_hash:
return True
# SECURE - always takes same time
import hmac
return hmac.compare_digest(password, stored_hash)
Always use constant-time comparison functions.
Q219: How do you handle password resets securely?
Answer: Secure password reset:
- Generate unique token - Use cryptographically secure random
- Set expiration - Token should expire (e.g., 1 hour)
- Send via email - Not SMS (SIM swapping risks)
- Store token hash - Don't store plain token
- One-time use - Invalidate after use
- Require password confirmation - When setting new password
import secrets
import hashlib
# Generate secure token
token = secrets.token_urlsafe(32)
# Store hash of token (not the token itself)
token_hash = hashlib.sha256(token.encode()).hexdigest()
# Send token to user's email
send_password_reset_email(user.email, token)
# When token received, verify and reset
if verify_token_hash(token, token_hash):
update_password(user, new_password)
Q220: What is pepper in password hashing?
Answer: Pepper is a secret key added to the password before hashing, stored separately from the database.
import os
import bcrypt
PEPPER = os.environ.get('PEPPER_SECRET') # Stored in config, not DB
def hash_password(password):
# Add pepper before hashing
return bcrypt.hashpw(PEPPER + password.encode(), bcrypt.gensalt())
def verify_password(password, hashed):
return bcrypt.checkpw(PEPPER + password.encode(), hashed)
Benefits:
- Even if database is compromised, passwords still need pepper
- Pepper should be stored in application config or HSM
Q221: What is salting in password hashing?
Answer: Salting adds random data to each password before hashing to ensure unique hashes.
# bcrypt does this automatically
bcrypt.hashpw(b"password", bcrypt.gensalt()) # Different each time!
# Manual salting (not recommended - use bcrypt)
import os
import hashlib
salt = os.urandom(32) # Generate random salt
hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
# Must store both salt and hash
stored_value = salt + hash
Q222: What is key stretching?
Answer: Key stretching is the technique of repeatedly applying a hash function to increase computation time.
# PBKDF2 uses key stretching
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode(),
salt,
iterations=100000 # More iterations = more secure but slower
)
Purpose:
- Makes brute force attacks impractical
- Each guess takes significant time
- Legitimate users barely notice the delay
Q223: What are the OWASP password storage guidelines?
Answer: OWASP recommends:
- Use Argon2id - Primary recommendation (if available)
- Use bcrypt - If Argon2 not available (work factor ≥10)
- Use scrypt - If memory-hard needed
- Use PBKDF2 - If required by NIST (iterations ≥120,000)
- Never use: MD5, SHA-1, SHA-256 (without iterations)
Additional:
- Use unique salt per password
- Use constant-time comparison
- Implement account lockout
- Use multi-factor authentication
Q224: How do you migrate from weak to strong hashing?
Answer: When upgrading password hashing:
- Keep old hashes - Continue verifying old format
- Detect algorithm - Store algorithm identifier
- Re-hash on login - When user logs in, re-hash with new algorithm
- Upgrade gradually - All passwords will eventually upgrade
def verify_and_upgrade(password, stored_hash):
# Detect algorithm from hash format
if stored_hash.startswith('$2a$') or stored_hash.startswith('$2b$'):
if bcrypt.checkpw(password.encode(), stored_hash.encode()):
# Old bcrypt - upgrade to Argon2
new_hash = argon2.hash(password)
save_new_hash(user, new_hash)
return True
elif stored_hash.startswith('$argon2'):
return argon2.verify(password, stored_hash)
return False
Q225: What is the difference between password hashing and encryption?
Answer:
| Aspect | Password Hashing | Encryption |
|---|---|---|
| Purpose | Verify without storing password | Protect data |
| Process | One-way, irreversible | Two-way, reversible |
| Key needed | No | Yes |
| Use for | Passwords | Sensitive data (SSN, credit cards) |
| Speed | Slow (intentional) | Fast |
You can encrypt password if you need to recover it, but hashing is preferred for authentication.
Q226: What is a hash collision?
Answer: A hash collision occurs when two different inputs produce the same hash output.
For passwords:
- Modern algorithms (bcrypt, Argon2) have no known practical collisions
- MD5 and SHA-1 have known collisions
Attackers might use collisions to:
- Find different password that validates to same hash
- But this is impractical with bcrypt/Argon2
Q227: What is client-side password hashing?
Answer: Client-side hashing adds extra security by hashing on the client before sending to server.
Flow:
- Client fetches salt from server
- Client hashes password with salt
- Client sends hash to server
- Server does additional hash (for defense in depth)
Benefits:
- Password never sent in plain text
- Reduces server load
- Protects against malicious servers
// Client-side example
async function hashPassword(password, salt) {
const encoder = new TextEncoder();
const data = encoder.encode(password + salt);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return arrayBufferToHex(hashBuffer);
}
Q228: What is bcrypt cost factor balancing?
Answer: Choosing the right cost factor:
Guidelines:
- Target: ~250ms for verification
- Start with cost 10-12
- Increase by 1 every 1-2 years
- Test on your hardware
import bcrypt
import time
# Test different costs
for cost in [10, 11, 12, 13]:
start = time.time()
bcrypt.hashpw(b"password", bcrypt.gensalt(rounds=cost))
elapsed = time.time() - start
print(f"Cost {cost}: {elapsed:.3f} seconds")
# Pick cost that takes ~250ms
Q229: How does Argon2 achieve memory hardness?
Answer: Argon2 uses a memory-hard algorithm:
- Initialize memory - Fill large memory block with pseudo-random data
- Process in passes - Each pass over memory depends on previous
- Use all memory - Can't optimize by using less memory
- Parallelization - Uses multiple CPU cores but still memory-bound
The memory cost (m) makes it expensive for:
- GPUs (limited memory)
- ASICs (memory is expensive)
- Parallel attacks (multiplied memory usage)
Q230: What is the future of password hashing?
Answer: Trends and future considerations:
- Argon2 becoming standard - OWASP recommended
- Quantum resistance - Post-quantum algorithms emerging
- Hardware security - TPM, secure enclaves
- Passkeys - Passwordless authentication gaining traction
- Continuous evaluation - Regular security audits
Best practices for future:
- Stay updated with OWASP recommendations
- Plan for algorithm migration
- Consider passwordless options
- Implement multi-factor authentication
14. Data Structures & Algorithms
Basic Level
Q231: What is Big-O Notation and why is it important?
Answer: Big-O notation describes the upper bound of an algorithm's time or space complexity. It tells us how an algorithm's performance scales as input size increases.
Common Complexities (from best to worst):
| Notation | Name | Example |
|---|---|---|
| O(1) | Constant | Array index access |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Single loop |
| O(n log n) | Linearithmic | Merge sort |
| O(n²) | Quadratic | Nested loops |
| O(2ⁿ) | Exponential | Recursive Fibonacci |
| O(n!) | Factorial | Permutations |
Example:
# O(1) - Constant time
def get_first_element(arr):
return arr[0]
# O(n) - Linear time
def find_max(arr):
max_val = arr[0]
for val in arr:
if val > max_val:
max_val = val
return max_val
# O(n²) - Quadratic time
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
Q232: What is a Stack?
Answer: A Stack is a LIFO (Last In, First Out) data structure. Think of it like a stack of plates - you can only add or remove from the top.
Operations:
push(item)- Add to top (O(1))pop()- Remove from top (O(1))peek()- View top without removing (O(1))
Python Implementation:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
print(stack.peek()) # 2
Use Cases: Function call stack, undo/redo, expression evaluation, DFS traversal.
Q233: What is a Queue?
Answer: A Queue is a FIFO (First In, First Out) data structure. Think of it like a line at a checkout counter.
Types:
- Simple Queue - Basic FIFO
- Deque (Double-ended Queue) - Add/remove from both ends
- Priority Queue - Elements have priority, higher priority dequeued first
Python Implementation:
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.popleft()
return None
def front(self):
return self.items[0] if self.items else None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Priority Queue using heapq
import heapq
class PriorityQueue:
def __init__(self):
self.heap = []
def enqueue(self, priority, item):
heapq.heappush(self.heap, (priority, item))
def dequeue(self):
if self.heap:
return heapq.heappop(self.heap)[1]
return None
# Usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue()) # 1
Q234: What is a Linked List?
Answer: A Linked List is a linear data structure where elements (nodes) are connected via pointers. Each node contains data and a reference to the next node.
Types:
- Singly Linked List - Each node points to next only
- Doubly Linked List - Each node points to both next and previous
Python Implementation:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete(self, data):
if not self.head:
return
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
def display(self):
elements = []
current = self.head
while current:
elements.append(str(current.data))
current = current.next
print(" -> ".join(elements) + " -> None")
def find(self, data):
current = self.head
position = 0
while current:
if current.data == data:
return position
current = current.next
position += 1
return -1
# Usage
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.prepend(0)
ll.display() # 0 -> 1 -> 2 -> 3 -> None
ll.delete(2)
ll.display() # 0 -> 1 -> 3 -> None
Time Complexities:
- Access: O(n)
- Search: O(n)
- Insert/Delete at head: O(1)
- Insert/Delete at tail: O(n) (without tail pointer)
Q235: What is a Binary Search Tree (BST)?
Answer: A BST is a hierarchical data structure where each node has at most two children. The left child is smaller, and the right child is larger than the parent node.
Properties:
- Left subtree contains smaller values
- Right subtree contains larger values
- No duplicate values (typically)
- In-order traversal gives sorted sequence
Python Implementation:
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
self.root = self._insert_recursive(self.root, val)
def _insert_recursive(self, node, val):
if not node:
return TreeNode(val)
if val < node.val:
node.left = self._insert_recursive(node.left, val)
else:
node.right = self._insert_recursive(node.right, val)
return node
def search(self, val):
return self._search_recursive(self.root, val)
def _search_recursive(self, node, val):
if not node or node.val == val:
return node is not None
if val < node.val:
return self._search_recursive(node.left, val)
return self._search_recursive(node.right, val)
def inorder(self):
result = []
self._inorder_recursive(self.root, result)
return result
def _inorder_recursive(self, node, result):
if node:
self._inorder_recursive(node.left, result)
result.append(node.val)
self._inorder_recursive(node.right, result)
def delete(self, val):
self.root = self._delete_recursive(self.root, val)
def _delete_recursive(self, node, val):
if not node:
return None
if val < node.val:
node.left = self._delete_recursive(node.left, val)
elif val > node.val:
node.right = self._delete_recursive(node.right, val)
else:
if not node.left:
return node.right
if not node.right:
return node.left
min_larger_node = node.right
while min_larger_node.left:
min_larger_node = min_larger_node.left
node.val = min_larger_node.val
node.right = self._delete_recursive(node.right, node.val)
return node
# Usage
bst = BST()
for val in [50, 30, 70, 20, 40, 60, 80]:
bst.insert(val)
print(bst.inorder()) # [20, 30, 40, 50, 60, 70, 80]
print(bst.search(40)) # True
print(bst.search(45)) # False
Q236: What is a Hash Map (Hash Table)?
Answer: A Hash Map stores key-value pairs using a hash function to compute an index into an array of buckets or slots.
Key Concepts:
- Hash Function: Converts key to array index
- Collision: When two keys hash to same index
- Collision Resolution: Chaining (linked lists) or Open Addressing (linear probing)
Python Implementation:
class HashMap:
def __init__(self, size=100):
self.size = size
self.buckets = [[] for _ in range(size)] # Chaining for collisions
def _hash(self, key):
return hash(key) % self.size
def put(self, key, value):
index = self._hash(key)
bucket = self.buckets[index]
# Update existing key
for i, (k, v) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
# Add new key-value
bucket.append((key, value))
def get(self, key):
index = self._hash(key)
bucket = self.buckets[index]
for k, v in bucket:
if k == key:
return v
return None
def remove(self, key):
index = self._hash(key)
bucket = self.buckets[index]
for i, (k, v) in enumerate(bucket):
if k == key:
del bucket[i]
return True
return False
def contains(self, key):
return self.get(key) is not None
def __len__(self):
return sum(len(bucket) for bucket in self.buckets)
# Usage
hm = HashMap()
hm.put("name", "John")
hm.put("age", 30)
hm.put("city", "NYC")
print(hm.get("name")) # John
print(hm.contains("age")) # True
hm.remove("age")
print(hm.get("age")) # None
Time Complexities (Average):
- Insert: O(1)
- Delete: O(1)
- Search: O(1)
Q237: What are Sorting Algorithms?
Answer: Sorting algorithms arrange elements in a specific order (usually ascending).
Common Sorting Algorithms:
# Bubble Sort - O(n²)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
# Merge Sort - O(n log n)
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Quick Sort - O(n log n) average, O(n²) worst
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Heap Sort - O(n log n)
import heapq
def heap_sort(arr):
heapq.heapify(arr)
return [heapq.heappop(arr) for _ in range(len(arr))]
# Usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Bubble:", bubble_sort(arr.copy()))
print("Merge:", merge_sort(arr.copy()))
print("Quick:", quick_sort(arr.copy()))
print("Heap:", heap_sort(arr.copy()))
Comparison:
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
Q238: What is Recursion?
Answer: Recursion is a technique where a function calls itself to solve smaller instances of the same problem.
Key Components:
- Base Case: Condition to stop recursion
- Recursive Case: Function calls itself with smaller input
Examples:
# Factorial - Classic Recursion
def factorial(n):
# Base case
if n <= 1:
return 1
# Recursive case
return n * factorial(n - 1)
# Fibonacci with Memoization
def fibonacci(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
# Fibonacci - Iterative (alternative)
def fibonacci_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
# Binary Search - Recursive
def binary_search_recursive(arr, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# Tree Traversals
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(node):
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
def preorder(node):
return [node.val] + preorder(node.left) + preorder(node.right) if node else []
def postorder(node):
return postorder(node.left) + postorder(node.right) + [node.val] if node else []
# Usage
print(factorial(5)) # 120
print(fibonacci(10)) # 55
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search_recursive(arr, 5, 0, len(arr)-1)) # 4
15. Python 3.12-3.14 Features
Basic Level
Q239: What are Type Hints in Python?
Answer: Type hints (introduced in PEP 484) allow you to annotate variables, function parameters, and return values with their expected types. They improve code readability and enable static type checking.
Basic Syntax:
# Variable type hints
name: str = "John"
age: int = 30
scores: list[int] = [90, 85, 88]
prices: dict[str, float] = {"apple": 1.5, "banana": 0.75}
# Function type hints
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
Optional and Union Types:
from typing import Optional, Union, List, Dict, Tuple
# Optional (can be None or the type)
def find_user(user_id: int) -> Optional[str]:
users = {1: "John", 2: "Jane"}
return users.get(user_id)
# Union (can be multiple types)
def parse_value(value: Union[str, int, float]) -> float:
return float(value)
# Literal (specific allowed values)
from typing import Literal
def move(direction: Literal["up", "down", "left", "right"]) -> Tuple[int, int]:
moves = {"up": (0, 1), "down": (0, -1), "left": (-1, 0), "right": (1, 0)}
return moves[direction]
Advanced Type Hints:
from typing import TypeVar, Generic, Protocol, Callable
# Generic types
T = TypeVar('T')
def first_element(lst: list[T]) -> Optional[T]:
return lst[0] if lst else None
# Protocol (structural subtyping)
class Readable(Protocol):
def read(self, size: int = -1) -> bytes:
...
def process_file(f: Readable) -> str:
return f.read().decode('utf-8')
# Callable type hints
def apply(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
result = apply(lambda a, b: a + b, 5, 3) # 8
# TypeAlias
Vector = list[float]
Matrix = list[list[float]]
def normalize(vector: Vector) -> Vector:
magnitude = sum(x**2 for x in vector) ** 0.5
return [x / magnitude for x in vector]
Q240: What are Dataclasses?
Answer: Dataclasses (introduced in Python 3.7) reduce boilerplate for creating classes that primarily store data. They automatically generate __init__, __repr__, __eq__, and other methods.
Basic Usage:
from dataclasses import dataclass
from typing import Optional
@dataclass
class User:
name: str
email: str
age: int
is_active: bool = True # Default value
# Usage
user = User("John", "john@example.com", 30)
print(user)
# User(name='John', email='john@example.com', age=30, is_active=True)
Advanced Dataclass Features:
from dataclasses import dataclass, field
from typing import List, Optional
from datetime import datetime
@dataclass
class Product:
id: int
name: str
price: float
tags: List[str] = field(default_factory=list) # Mutable default
created_at: datetime = field(default_factory=datetime.now)
@property
def formatted_price(self) -> str:
return f"${self.price:.2f}"
@dataclass
class Order:
id: int
customer: str
products: List[Product] = field(default_factory=list)
total: float = 0.0
def __post_init__(self):
# Calculate total after initialization
self.total = sum(p.price for p in self.products)
def add_product(self, product: Product):
self.products.append(product)
self.total += product.price
# Frozen (immutable) dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def distance_from_origin(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5
# Usage
order = Order(
id=1,
customer="John",
products=[
Product(1, "Laptop", 999.99),
Product(2, "Mouse", 29.99)
]
)
print(order)
# Order(id=1, customer='John', products=[...], total=1029.98)
point = Point(3, 4)
print(point.distance_from_origin()) # 5.0
# point.x = 5 # Raises FrozenInstanceError
Q241: What is the Walrus Operator (:=)?
Answer: The walrus operator (assignment expression) allows you to assign and return a value in the same expression. Introduced in Python 3.8.
Before and After:
# Without walrus operator
n = len(data)
if n > 10:
print(f"Large dataset: {n}")
# With walrus operator
if (n := len(data)) > 10:
print(f"Large dataset: {n}")
# List comprehension with walrus
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Without walrus - calculate square twice
squares = [x**2 for x in numbers if x**2 > 50]
# With walrus - calculate once
squares = [sq for x in numbers if (sq := x**2) > 50]
# Loop with walrus
while (line := input("Enter text: ")) != "quit":
print(f"You entered: {line}")
# Regular expression with walrus
import re
pattern = re.compile(r'(\w+)@(\w+)\.(\w+)')
text = "Contact: john@example.com"
if match := pattern.search(text):
print(f"User: {match.group(1)}") # john
Q242: What is Pattern Matching (Python 3.10+)?
Answer: Pattern matching (introduced in Python 3.10) allows you to compare a value against patterns and execute code based on which pattern matches. Similar to switch-case in other languages but much more powerful.
Basic Syntax:
# Simple match
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown"
# Multiple patterns
def grade(score):
match score:
case 9 | 10:
return "A"
case 7 | 8:
return "B"
case 5 | 6:
return "C"
case _:
return "F"
Structural Pattern Matching:
from dataclasses import dataclass
from typing import Union
@dataclass
class Point:
x: int
y: int
@dataclass
class Circle:
center: Point
radius: int
@dataclass
class Rectangle:
width: int
height: int
Shape = Union[Point, Circle, Rectangle]
def describe_shape(shape: Shape):
match shape:
case Point(0, 0):
print("Origin point")
case Point(x, y):
print(f"Point at ({x}, {y})")
case Circle(center=Point(x, y), radius=r):
print(f"Circle at ({x}, {y}) with radius {r}")
case Rectangle(width=w, height=h):
print(f"Rectangle {w}x{h}")
# Dictionary patterns
def get_config(config):
match config:
case {"host": host, "port": port}:
return f"Server: {host}:{port}"
case {"path": path} if path.startswith("/api"):
return f"API endpoint: {path}"
case _:
return "Unknown configuration"
# Class patterns
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def classify(person: Person):
match person:
case Person(name=str(), age=a) if a < 18:
print(f"{name} is a minor")
case Person(name=name, age=age):
print(f"{name} is {age} years old")
Q243: What are Decorators with Arguments?
Answer: Decorators with arguments require a three-level function: outer function takes arguments, middle function takes the decorated function, inner function performs the decoration.
Structure:
# Decorator without arguments
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
# Decorator WITH arguments
def decorator_with_args(arg1, arg2):
def actual_decorator(func):
def wrapper(*args, **kwargs):
print(f"Decorator args: {arg1}, {arg2}")
print("Before function")
result = func(*args, **kwargs)
print("After function")
return result
return wrapper
return actual_decorator
# Usage
@decorator_with_args("value1", "value2")
def say_hello(name):
print(f"Hello, {name}!")
say_hello("John")
# Output:
# Decorator args: value1, value2
# Before function
# Hello, John!
# After function
Practical Examples:
import time
from functools import wraps
# Retry decorator
def retry(max_attempts=3, delay=1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
print(f"Attempt {attempt + 1} failed: {e}")
time.sleep(delay)
return None
return wrapper
return decorator
# Rate limiter decorator
def rate_limit(calls_per_second):
import time
def decorator(func):
last_called = [0.0]
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
if elapsed < 1.0 / calls_per_second:
time.sleep(1.0 / calls_per_second - elapsed)
last_called[0] = time.time()
return func(*args, **kwargs)
return wrapper
return decorator
# Cache decorator
from functools import lru_cache
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
# Usage
@retry(max_attempts=3, delay=2)
def fetch_data(url):
print(f"Fetching {url}")
if "fail" in url:
raise ConnectionError("Failed!")
return "data"
@rate_limit(calls_per_second=2)
def api_call():
print("API called")
@timer
def slow_function():
time.sleep(1)
return "Done"
16. Design Patterns
Basic Level
Q244: What is the Factory Pattern?
Answer: The Factory Pattern provides an interface for creating objects without specifying their exact classes. It delegates the creation logic to subclasses or helper functions.
Simple Factory:
from abc import ABC, abstractmethod
# Product interface
class Notification(ABC):
@abstractmethod
def send(self, message: str):
pass
# Concrete products
class EmailNotification(Notification):
def send(self, message: str):
print(f"📧 Sending email: {message}")
class SMSNotification(Notification):
def send(self, message: str):
print(f"📱 Sending SMS: {message}")
class PushNotification(Notification):
def send(self, message: str):
print(f"🔔 Sending push: {message}")
# Factory
class NotificationFactory:
@staticmethod
def create_notification(notification_type: str) -> Notification:
notifications = {
"email": EmailNotification,
"sms": SMSNotification,
"push": PushNotification
}
notification_class = notifications.get(notification_type.lower())
if not notification_class:
raise ValueError(f"Unknown notification type: {notification_type}")
return notification_class()
# Usage
factory = NotificationFactory()
notification = factory.create_notification("email")
notification.send("Hello World!")
Factory Method:
from abc import ABC, abstractmethod
class Transport(ABC):
@abstractmethod
def deliver(self):
pass
class Truck(Transport):
def deliver(self):
print("🚚 Delivering by road")
class Ship(Transport):
def deliver(self):
print("🚢 Delivering by sea")
class Plane(Transport):
def deliver(self):
print("✈️ Delivering by air")
# Factory method in base class
class Logistics(ABC):
@abstractmethod
def create_transport(self) -> Transport:
pass
def plan_delivery(self):
transport = self.create_transport()
transport.deliver()
# Concrete factories
class RoadLogistics(Logistics):
def create_transport(self) -> Transport:
return Truck()
class SeaLogistics(Logistics):
def create_transport(self) -> Transport:
return Ship()
class AirLogistics(Logistics):
def create_transport(self) -> Transport:
return Plane()
# Usage
logistics: Logistics = RoadLogistics()
logistics.plan_delivery() # 🚚 Delivering by road
Q245: What is the Observer Pattern?
Answer: The Observer Pattern defines a one-to-many dependency between objects, so when one object changes state, all its dependents are notified automatically.
Implementation:
from abc import ABC, abstractmethod
from typing import List
class Observer(ABC):
@abstractmethod
def update(self, message: str):
pass
class Subject(ABC):
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._latest_news = ""
@property
def latest_news(self):
return self._latest_news
@latest_news.setter
def latest_news(self, value):
self._latest_news = value
self.notify(f"Breaking: {value}")
class NewsChannel(Observer):
def __init__(self, name: str):
self.name = name
def update(self, message: str):
print(f"{self.name} received: {message}")
class SocialMedia(Observer):
def __init__(self, platform: str):
self.platform = platform
def update(self, message: str):
print(f"Posting to {self.platform}: {message}")
# Usage
news_agency = NewsAgency()
cnn = NewsChannel("CNN")
bbc = NewsChannel("BBC")
twitter = SocialMedia("Twitter")
news_agency.attach(cnn)
news_agency.attach(bbc)
news_agency.attach(twitter)
news_agency.latest_news = "Python 3.14 released!"
# CNN received: Breaking: Python 3.14 released!
# BBC received: Breaking: Python 3.14 released!
# Posting to Twitter: Breaking: Python 3.14 released!
Q246: What is the Strategy Pattern?
Answer: The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
Implementation:
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: float) -> bool:
pass
class CreditCardPayment(PaymentStrategy):
def __init__(self, card_number: str, cvv: str):
self.card_number = card_number
self.cvv = cvv
def pay(self, amount: float) -> bool:
print(f"💳 Paying ${amount:.2f} with Credit Card {self.card_number[-4:]}")
return True
class PayPalPayment(PaymentStrategy):
def __init__(self, email: str):
self.email = email
def pay(self, amount: float) -> bool:
print(f"🅿️ Paying ${amount:.2f} with PayPal ({self.email})")
return True
class CryptoPayment(PaymentStrategy):
def __init__(self, wallet_address: str):
self.wallet_address = wallet_address
def pay(self, amount: float) -> bool:
print(f"🪙 Paying ${amount:.2f} with Crypto to {self.wallet_address[:10]}...")
return True
class ShoppingCart:
def __init__(self):
self.items = []
self.payment_strategy: PaymentStrategy = None
def add_item(self, item: str, price: float):
self.items.append((item, price))
def set_payment_strategy(self, strategy: PaymentStrategy):
self.payment_strategy = strategy
def checkout(self):
total = sum(price for _, price in self.items)
print(f"\nTotal: ${total:.2f}")
if self.payment_strategy:
return self.payment_strategy.pay(total)
print("No payment method selected!")
return False
# Usage
cart = ShoppingCart()
cart.add_item("Laptop", 999.99)
cart.add_item("Mouse", 29.99)
cart.set_payment_strategy(CreditCardPayment("4111111111111111", "123"))
cart.checkout()
cart.set_payment_strategy(PayPalPayment("user@email.com"))
cart.checkout()
Q247: What is the Repository Pattern?
Answer: The Repository Pattern abstracts the data layer, providing a collection-like interface for accessing domain objects. It separates business logic from data access.
Implementation:
from abc import ABC, abstractmethod
from typing import List, Optional, TypeVar, Generic
T = TypeVar('T')
class Repository(ABC, Generic[T]):
@abstractmethod
def get_by_id(self, id: int) -> Optional[T]:
pass
@abstractmethod
def get_all(self) -> List[T]:
pass
@abstractmethod
def add(self, entity: T) -> T:
pass
@abstractmethod
def update(self, entity: T) -> T:
pass
@abstractmethod
def delete(self, id: int) -> bool:
pass
# Domain models
class User:
def __init__(self, id: int, name: str, email: str):
self.id = id
self.name = name
self.email = email
def __repr__(self):
return f"User(id={self.id}, name={self.name})"
# In-memory implementation
class InMemoryUserRepository(Repository[User]):
def __init__(self):
self._users = {}
self._next_id = 1
def get_by_id(self, id: int) -> Optional[User]:
return self._users.get(id)
def get_all(self) -> List[User]:
return list(self._users.values())
def add(self, user: User) -> User:
user.id = self._next_id
self._users[user.id] = user
self._next_id += 1
return user
def update(self, user: User) -> User:
if user.id in self._users:
self._users[user.id] = user
return user
def delete(self, id: int) -> bool:
if id in self._users:
del self._users[id]
return True
return False
# Service layer using repository
class UserService:
def __init__(self, repository: Repository[User]):
self.repository = repository
def create_user(self, name: str, email: str) -> User:
user = User(None, name, email)
return self.repository.add(user)
def get_user(self, id: int) -> Optional[User]:
return self.repository.get_by_id(id)
def update_email(self, id: int, new_email: str) -> Optional[User]:
user = self.repository.get_by_id(id)
if user:
user.email = new_email
return self.repository.update(user)
return None
# Usage
repo = InMemoryUserRepository()
service = UserService(repo)
user1 = service.create_user("John", "john@example.com")
user2 = service.create_user("Jane", "jane@example.com")
print(service.get_user(1)) # User(id=1, name=John)
print(service.get_all()) # [User(id=1, name=John), User(id=2, name=Jane)]
17. Testing
Basic Level
Q248: What is pytest and why use it?
Answer: pytest is a Python testing framework that makes it easy to write simple and scalable test cases. It provides features like fixtures, parametrization, markers, and detailed assertion introspection.
Basic Structure:
# my_module.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# test_my_module.py
import pytest
from my_module import add, subtract, multiply, divide
# Basic tests
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_subtract():
assert subtract(5, 3) == 2
def test_multiply():
assert multiply(4, 5) == 20
def test_divide():
assert divide(10, 2) == 5
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
# Parametrized tests
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
(100, 200, 300)
])
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
# Testing with fixtures
@pytest.fixture
def sample_data():
return {"name": "John", "age": 30}
def test_with_fixture(sample_data):
assert sample_data["name"] == "John"
assert sample_data["age"] == 30
Q249: What are pytest Fixtures?
Answer: Fixtures provide a way to set up and tear down data or resources needed for tests. They can be scoped to function, class, module, or session.
Fixture Examples:
import pytest
from datetime import datetime
# Basic fixture
@pytest.fixture
def empty_list():
return []
# Fixture with setup/teardown
@pytest.fixture
def database_connection():
# Setup
print("\nSetting up database connection")
conn = {"connected": True, "data": []}
yield conn
# Teardown
print("\nClosing database connection")
conn["connected"] = False
# Fixture with parameters
@pytest.fixture(params=[1, 2, 3])
def number(request):
return request.param
def test_with_parametrized_fixture(number):
assert number in [1, 2, 3]
# Session-scoped fixture
@pytest.fixture(scope="session")
def app_config():
return {"debug": True, "version": "1.0.0"}
# Class-scoped fixture
class TestUserService:
@pytest.fixture(scope="class")
def user_service(self):
return UserService()
@pytest.fixture
def sample_user(self):
return {"name": "Test User", "email": "test@example.com"}
def test_create_user(self, user_service, sample_user):
result = user_service.create(**sample_user)
assert result["name"] == sample_user["name"]
def test_get_user(self, user_service, sample_user):
created = user_service.create(**sample_user)
retrieved = user_service.get(created["id"])
assert retrieved is not None
# Auto-use fixtures
@pytest.fixture(autouse=True)
def setup_teardown():
print("\n[Setup]")
yield
print("\n[Teardown]")
conftest.py (Shared Fixtures):
# conftest.py - automatically discovered by pytest
import pytest
from app import create_app, db
@pytest.fixture(scope="session")
def app():
app = create_app()
app.config["TESTING"] = True
return app
@pytest.fixture(scope="session")
def client(app):
return app.test_client()
@pytest.fixture
def runner(app):
return app.test_cli_runner()
@pytest.fixture
def init_database():
db.create_all()
yield db
db.drop_all()
Q250: What is Mocking in Python?
Answer: Mocking replaces real objects with fake objects to isolate the code under test. It allows you to test components in isolation without dependencies.
Using unittest.mock:
import pytest
from unittest.mock import Mock, patch, MagicMock, call
# Basic Mock
def test_basic_mock():
mock_obj = Mock()
mock_obj.method.return_value = "mocked result"
result = mock_obj.method()
assert result == "mocked result"
mock_obj.method.assert_called_once()
# Mock with arguments
def test_mock_with_args():
mock_calc = Mock()
mock_calc.calculate.side_effect = lambda x, y: x + y
assert mock_calc.calculate(2, 3) == 5
assert mock_calc.calculate(10, 20) == 30
# Mocking class attributes
def test_mock_class_attribute():
mock_obj = Mock()
mock_obj.name = "Test Object"
mock_obj.get_value.return_value = 42
assert mock_obj.get_value() == 42
# Using patch as decorator
@patch('my_module.UserService')
def test_with_patch(mock_user_service):
mock_instance = Mock()
mock_instance.get_user.return_value = {"id": 1, "name": "John"}
mock_user_service.return_value = mock_instance
from my_module import get_user_by_id
result = get_user_by_id(1)
assert result["name"] == "John"
mock_instance.get_user.assert_called_once_with(1)
# Using patch as context manager
def test_with_patch_context():
with patch('my_module.Database') as mock_db:
mock_db.get_connection.return_value = Mock()
# Test code here
pass
# Mocking properties
def test_mock_property():
mock_obj = Mock()
mock_obj.price = 100 # Property value
# For read-only properties
type(mock_obj).discount = property(lambda self: self.price * 0.1)
assert mock_obj.discount == 10
# Spy - Mock that calls real methods
def test_spy():
original_func = my_module.calculate_total
with patch.object(my_module, 'calculate_total', wraps=original_func) as spy_func:
my_module.process([1, 2, 3])
spy_func.assert_called()
# Async mocking
@pytest.mark.asyncio
async def test_async_mock():
mock_async = AsyncMock()
mock_async.fetch_data.return_value = {"result": "data"}
result = await mock_async.fetch_data()
assert result == {"result": "data"}
Q251: What is Test-Driven Development (TDD)?
Answer: TDD is a development approach where you write tests before writing the code. The cycle is: Red (write failing test) → Green (write minimal code to pass) → Refactor.
TDD Cycle:
# Step 1: RED - Write a failing test
# test_stack.py
import pytest
from stack import Stack
def test_stack_is_empty():
stack = Stack()
assert stack.is_empty() == True
def test_stack_push():
stack = Stack()
stack.push(1)
assert stack.is_empty() == False
assert stack.peek() == 1
def test_stack_pop():
stack = Stack()
stack.push(42)
assert stack.pop() == 42
assert stack.is_empty() == True
def test_stack_pop_empty():
stack = Stack()
with pytest.raises(IndexError):
stack.pop()
# Step 2: GREEN - Write minimal code to pass
# stack.py
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
# Step 3: REFACTOR - Improve code while keeping tests passing
class Stack:
def __init__(self):
self._items = []
self._size = 0
def push(self, item):
self._items.append(item)
self._size += 1
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
self._size -= 1
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self._items[-1]
def is_empty(self):
return self._size == 0
def size(self):
return self._size
18. Git & Version Control
Basic Level
Q252: What are Git Branching Strategies?
Answer: Git branching strategies define how teams organize their workflow using branches. Common strategies include Git Flow, GitHub Flow, and Trunk-Based Development.
Git Flow:
main (production)
└── release/1.0.0
└── develop
├── feature/user-auth
├── feature/payment
└── hotfix/login-bug
# Git Flow Commands
git flow init
git flow feature start user-auth
git flow feature finish user-auth
git flow release start 1.0.0
git flow release finish 1.0.0
git flow hotfix start login-bug
git flow hotfix finish login-bug
GitHub Flow (Simplified):
# 1. Create feature branch
git checkout main
git pull origin main
git checkout -b feature/new-feature
# 2. Make changes and commit
git add .
git commit -m "feat: add new feature"
# 3. Push and create PR
git push -u origin feature/new-feature
# 4. Code review and merge
# Via GitHub UI: Create Pull Request → Review → Merge
# 5. Delete branch
git branch -d feature/new-feature
git push origin --delete feature/new-feature
Trunk-Based Development:
# Short-lived branches (< 1 day)
git checkout main
git pull origin main
git checkout -b fix/quick-bug-fix
# Commit and push immediately for CI
git add .
git commit -m "fix: resolve issue #123"
git push origin fix/quick-bug-fix
# Merge via PR (keep main green)
# Feature flags for incomplete features
Q253: What is the difference between Merge and Rebase?
Answer: Both integrate changes from one branch into another, but they do it differently.
Merge:
# Before:
# main: A - B - C
# \
# feature: D - E
git checkout main
git merge feature
# After:
# main: A - B - C - M
# \ /
# feature: D - E
- Creates a merge commit
- Preserves full history
- Non-destructive
- Can create cluttered history
Rebase:
# Before:
# main: A - B - C
# \
# feature: D - E
git checkout feature
git rebase main
# After:
# main: A - B - C
# \
# feature: D' - E'
# Then merge feature into main (fast-forward)
git checkout main
git merge feature
- Replays commits on new base
- Creates linear history
- Rewrites commit history
- Never rebase public/shared branches!
Interactive Rebase:
# Rebase last 5 commits
git rebase -i HEAD~5
# Commands in interactive mode:
# pick - use commit
# reword - change commit message
# edit - stop for amending
# squash - combine with previous
# fixup - like squash, discard commit message
# drop - remove commit
# Example interactive rebase:
# pick 123abc Add feature X
# reword 456def Fix typo
# squash 789ghi WIP work
# fixup 012jkl Cleanup
# drop 345mno Abandon this
Q254: What are Git Hooks?
Answer: Git hooks are scripts that run automatically at specific points in the Git workflow. They live in the .git/hooks directory.
Common Hooks:
# pre-commit - Run before each commit
#!/bin/bash
# .git/hooks/pre-commit
# Check for console.log in JavaScript files
if git diff --cached --name-only | grep '\.js$' | xargs grep -l 'console\.log'; then
echo "Error: console.log found in JavaScript files"
exit 1
fi
# Run linting
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed"
exit 1
fi
# Commit message hook (commit-msg)
#!/bin/bash
# .git/hooks/commit-msg
commit_msg=$(cat $1)
pattern="^(feat|fix|docs|style|refactor|test|chore): "
if ! [[ $commit_msg =~ $pattern ]]; then
echo "Invalid commit message format!"
echo "Expected: type: description"
echo "Types: feat, fix, docs, style, refactor, test, chore"
exit 1
fi
# pre-push - Run before pushing
#!/bin/bash
# .git/hooks/pre-push
# Run tests before pushing
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Push rejected."
exit 1
fi
# post-merge - Run after merge
#!/bin/bash
# .git/hooks/post-merge
# Auto-install dependencies if package.json changed
if [ -f package.json ]; then
npm install
fi
Using Husky (npm package):
# Install husky
npm install husky --save-dev
# Initialize
npx husky install
# Add a hook
npx husky add .husky/pre-commit "npm run lint"
npx husky add .husky/commit-msg "npx commitlint --edit $1"
npx husky add .husky/pre-push "npm test"
Q255: Common Git Commands Reference
# === Basics ===
git init # Initialize repository
git clone <url> # Clone repository
git status # Show working tree status
git add <file> # Stage file(s)
git commit -m "message" # Commit with message
git push # Push to remote
git pull # Pull from remote
# === Branching ===
git branch # List branches
git branch <name> # Create branch
git checkout <branch> # Switch branch
git checkout -b <branch> # Create and switch
git branch -d <branch> # Delete branch
git merge <branch> # Merge branch into current
# === Viewing History ===
git log # Show commit history
git log --oneline # Compact log
git log --graph --all # Visual branch graph
git diff # Show unstaged changes
git diff --staged # Show staged changes
git show <commit> # Show commit details
# === Undo ===
git reset --soft HEAD~1 # Undo last commit (keep changes)
git reset --hard HEAD~1 # Undo last commit (discard changes)
git revert <commit> # Create new commit that undoes previous
git checkout -- <file> # Discard changes to file
# === Stashing ===
git stash # Stash changes
git stash pop # Apply and remove stash
git stash list # List stashes
git stash drop # Remove stash
# === Advanced ===
git cherry-pick <commit> # Apply specific commit
git tag v1.0.0 # Create tag
git fetch --all # Fetch all remotes
git clean -fd # Remove untracked files
# === Submodules ===
git submodule add <url> # Add submodule
git submodule update --init # Update submodule
# === Git Aliases ===
git config --global alias.st "status"
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.lg "log --oneline --graph --all"
19. Python 3.13 - Free-Threading & JIT
Basic Level
Q256: What is Free-Threading in Python 3.13?
Answer: Python 3.13 introduces experimental support for running Python without the Global Interpreter Lock (GIL), allowing true multi-threaded parallelism. This is enabled with the --disable-gil flag.
Why the GIL Existed:
- The GIL (Global Interpreter Lock) prevented multiple threads from executing Python bytecode simultaneously
- It simplified CPython internals and made extension development easier
- But it limited Python to one CPU core for CPU-bound tasks
How Free-Threading Works:
# Running with free-threading (Python 3.13+)
# python --disable-gil script.py
# Checking at runtime
import sys
print(sys._is_gil_enabled()) # False in free-threaded mode
# The free-threaded mode uses:
# - Per-object locking instead of global GIL
# - Biased reference counting for better performance
# - Mimalloc for memory allocation
Performance Implications:
# Free-threading is beneficial for:
# 1. CPU-bound parallel workloads
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import multiprocessing
def cpu_intensive_task(n):
return sum(i * i for i in range(n))
# With free-threading, threads can now truly run in parallel
# for CPU-bound tasks (previously needed multiprocessing)
# 2. I/O-bound tasks with many waiting periods
async def fetch_all(urls):
import aiohttp
async with aiohttp.ClientSession() as session:
tasks = [fetch_one(session, url) for url in urls]
return await asyncio.gather(*tasks)
# Note: Most existing code doesn't need free-threading
# Threads still don't help for typical web apps due to GIL contention
Q257: What is the JIT Compiler in Python 3.13?
Answer: Python 3.13 includes an experimental JIT compiler that can improve performance for long-running applications.
Enabling the JIT:
# Enable JIT at runtime
python -X jit=on script.py
# Or with environment variable
export PYTHON_JIT=1
python script.py
How it Works:
# The JIT uses copy-and-patch compilation:
# 1. Interpreter runs code normally initially
# 2. Hot paths (frequently executed) are identified
# 3. Machine code is generated and cached
# 4. Future calls use compiled code directly
# Currently optional and experimental
# Not as aggressive as PyPy or numba
# For CPU-intensive numeric code, consider:
# - NumPy (vectorized operations)
# - Cython (C extensions)
# - Numba (JIT for numerical Python)
Q258: What are Other Python 3.13 Features?
Answer: Python 3.13 includes several improvements:
# 1. Improved Error Messages
# Now shows colored tracebacks by default
# Better suggestions for common mistakes
# 2. ReadOnly Types (PEP 705)
from typing import ReadOnly
class Config:
def __init__(self):
self._data: ReadOnly[dict] = {"key": "value"}
# 3. TypeIs (PEP 742)
from typing import TypeIs
def is_str_list(val: list[object]) -> TypeIs[list[str]]:
return all(isinstance(x, str) for x in val)
# 4. Improved Interactive REPL
# Multi-line editing, color support, auto-indentation
# 5. Naked Docstrings
# Docstrings can now be unindented automatically
def example():
"""
This is a naked docstring.
It will be cleaned up automatically.
"""
pass
# 6. Pathlib Improvements
from pathlib import Path
# glob with recursive option
list(Path(".").rglob("*.py"))
# 7. copy.replace() (PEP 690)
from copy import replace
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str = "unknown"
# Create modified copy
user2 = replace(user1, email="new@example.com")
# 8. Improved typing for generics
# Better type inference in various scenarios
20. Context Managers & Iterators
Basic Level
Q259: What is a Context Manager?
Answer: Context managers ensure proper resource cleanup by defining __enter__ and __exit__ methods. They're used with the with statement.
Basic Implementation:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# Return True to suppress exceptions
return False
# Usage
with FileManager("test.txt", "w") as f:
f.write("Hello, World!")
# Using contextlib
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f"Acquiring {name}")
resource = {"name": name, "value": 42}
try:
yield resource
finally:
print(f"Releasing {name}")
with managed_resource("database") as res:
print(f"Using {res['name']}")
# Suppressing exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("nonexistent.txt")
Q260: What are Iterators and Generators?
Answer: Iterators are objects that yield items one at a time. Generators are functions that use yield to create iterators.
Iterator Protocol:
class Counter:
def __init__(self, max_val):
self.max_val = max_val
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max_val:
raise StopIteration
self.current += 1
return self.current
for num in Counter(5):
print(num) # 1, 2, 3, 4, 5
# Generator Function
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num)
# Generator Expression
squares = (x**2 for x in range(10) if x % 2 == 0)
for sq in squares:
print(sq)
# itertools module
from itertools import count, cycle, chain, islice, takewhile
# Infinite counter
for i in islice(count(10), 5): # 10, 11, 12, 13, 14
print(i)
# Cycle through values
colors = cycle(["red", "green", "blue"])
# Chain iterables
combined = chain([1, 2], [3, 4], [5, 6])
# Take while condition is true
positive = list(takewhile(lambda x: x > 0, [5, 3, 1, -1, -3]))
# [5, 3, 1]
Quick Reference
Common Python Commands
# Run Python
python3 file.py
# Install package
pip install package-name
uv pip install package-name
# Virtual environment
python -m venv env
source env/bin/activate
Common PHP/Laravel Commands
# Run PHP server
php -S localhost:8000
# Laravel
php artisan serve
php artisan make:model ModelName
php artisan migrate
Common Database Commands
-- Select
SELECT * FROM users;
-- Insert
INSERT INTO users (name) VALUES ('John');
-- Update
UPDATE users SET name='Jane' WHERE id=1;
-- Delete
DELETE FROM users WHERE id=1;
End of Guide
21. Data Science: Pandas, NumPy, Polars
Q261: How does NumPy's memory model differ from Python lists?
- A: NumPy uses contiguous blocks of homogeneous memory, allowing for CPU cache optimizations and SIMD instructions. Python lists store pointers to objects scattered in memory, incurring overhead for dereferencing and type checking.
Q262: What is the benefit of Polars' Lazy Evaluation?
- A: It allows the query optimizer to perform predicate and projection pushdown—filtering and selecting columns at the source (like a database) to minimize the data loaded into memory.
Q263: How do you optimize Pandas memory usage?
- A: By downcasting numerical types (e.g.,
float64tofloat32), using thecategorydtype for low-cardinality strings, and loading only necessary columns viausecols.