Python Interview Concepts
Coding & Logic·intermediate·~25 min read
- python
- interview
- generators
- decorators
- comprehensions
- oop
- concurrency
What you'll learn
1. Comprehensions
Comprehensions provide concise syntax for creating collections from iterables.
List Comprehension
Dictionary Comprehension
Set Comprehension
There Is No Tuple Comprehension
Key insight: Parentheses with a comprehension-like syntax always produce a generator expression, never a tuple. ---
2. Generators
Generators are functions that produce a sequence of values lazily — yielding one value at a time instead of computing everything upfront and returning a list.
How yield Works
Generator State Machine
Independent Instances
Each call to a generator function creates a new, independent iterator:
Generator Expressions vs List Comprehensions
When to use generators: - Processing large datasets that don't fit in memory - Infinite sequences - Pipeline processing (chaining transformations) - When you only need to iterate once
Generator Pipeline Pattern
---
3. Decorators
A decorator is a function that takes a function as input and returns a modified function. It's syntactic sugar for wrapping behavior around existing functions.
Basic Decorator Pattern
The Problem: Lost Metadata
The Fix: functools.wraps
Always use @wraps(func) — it preserves: - name — function name - doc — docstring - module — module where defined - qualname — qualified name - dict — function attributes
Decorator With Parameters
When you need a decorator that accepts arguments, you need three levels of nesting: Why three levels?
Class as Decorator (using call)
Advantage of class decorators: Can maintain state between calls (like the count above).
Common Built-in Decorators
| Decorator | Purpose | |-----------|---------| | @staticmethod | No access to instance or class | | @classmethod | Receives class (cls) as first arg | | @property | Getter method accessible as attribute | | @abstractmethod | Must be ove…
Stacking Decorators
---
4. Closures & First-Class Functions
Functions as First-Class Objects
In Python, functions are objects — they can be assigned to variables, passed as arguments, and returned from other functions.
Closures
A closure is a function that remembers the variables from its enclosing scope even after that scope has finished executing. Why count = [start] instead of count = start? The inner function can read outer variables freely, but assigning t…
Closure vs Class (Interview Comparison)
---
5. The call Method
Making class instances callable like functions. Use cases for call: - Stateful functions (maintain state between invocations) - Strategy pattern (interchangeable callable objects) - Decorators implemented as classes - Creating function-l…
6. Private Variables & Naming Conventions
Python has no true private variables — it uses naming conventions: | Convention | Meaning | Behavior | |-----------|---------|----------| | name | Public | Accessible everywhere | | name | Protected (convention) | "Don't access from outs…
7. Class Variables vs Instance Variables
The Mutable Class Variable Trap
---
8. Static Methods vs Class Methods
| Type | First arg | Can access | |------|-----------|-----------| | Instance method | self | Instance + class vars | | Class method | cls | Class vars, create instances | | Static method | None | Nothing implicitly | When to use classme…
9. Operator Overloading
Python lets you define how operators work with your objects using dunder methods: | Operator | Method | Operator | Method | |----------|--------|----------|--------| | + | add | == | eq | | - | sub | != | ne | | | mul | | gt | | [] | g…
10. Abstract Classes & Interfaces
Python uses abc (Abstract Base Classes) module for interfaces: Key points: - Cannot instantiate a class with unimplemented abstract methods - Subclass MUST implement all abstract methods or remain abstract itself - ABC can have concrete…
Protocol (Python 3.8+) — Structural Typing
Protocol vs ABC: Protocol doesn't require inheritance — any class with matching methods satisfies it (duck typing formalized in type system). ---
11. The Global Interpreter Lock (GIL)
The GIL is a mutex that allows only one thread to execute Python bytecode at a time, even on multi-core machines.
What It Means
Why It Exists
- CPython's memory management (reference counting) is not thread-safe - The GIL simplifies the C extension API - Removing it would slow down single-threaded programs (~30% overhead)
Impact
| Workload | Threading helps? | Why | |----------|-----------------|-----| | CPU-bound (computation) | No | GIL blocks parallel execution | | I/O-bound (network, disk) | Yes | GIL released during I/O waits |
Solutions for CPU-Bound Work
Threading Still Works for I/O
Key Interview Points About GIL
- GIL is specific to CPython (not Jython, IronPython, or PyPy-STM) - asyncio doesn't bypass the GIL — it's cooperative concurrency for I/O - Python 3.12+ has experimental "per-interpreter GIL" (sub-interpreters) - Python 3.13+ has experi…
12. Web Framework Concepts (Django/Flask)
Middleware
Middleware is a framework component that processes every request/response globally — before it reaches the view and after the view returns. Common middleware uses: - Authentication/Authorization check - CSRF token validation - Session ha…
CSRF (Cross-Site Request Forgery) Protection
CSRF tokens prevent malicious sites from submitting forms on behalf of authenticated users.
WSGI and Application Servers
| Component | Role | |-----------|------| | WSGI | Standard interface between web servers and Python apps | | Gunicorn | WSGI HTTP server — spawns multiple worker processes | | Nginx | Reverse proxy — handles static files, TLS, load bala…
MVC/MVT Architecture
| Django (MVT) | Traditional MVC | Role | |-------------|----------------|------| | View | Controller | Handles request logic | | Template | View | Renders response | | Model | Model | Data + business logic |
Unit Testing
---
Summary
| Concept | Key Takeaway | |---------|-------------| | Comprehensions | Concise collection creation; () = generator not tuple | | Generators | Lazy evaluation via yield; O(1) memory for large sequences | | Decorators | Function wrapping;…