LearningTech

Py

Python & Web Frameworks — Interview Guide

Styled HTML Last generated: December 11, 2025

Python Core Concepts

Is Python compiled or interpreted?

Python source (.py) is compiled to bytecode (.pyc) and executed by the Python Virtual Machine (PVM). It behaves like a hybrid: compilation to bytecode + interpretation by the VM.

Case sensitivity

Yes — identifiers are case-sensitive (e.g., Var != var).

Indentation

Python uses indentation to define blocks. It is required — improper indentation raises IndentationError.

self in methods

self is the conventional first parameter in instance methods, referencing the current object. It allows access to attributes and other methods.

Docstrings

Docstrings are string literals placed immediately after definitions (module, class, function) used for documentation. Accessible via .__doc__.

Memory Management & Garbage Collection

Private heap & pymalloc

Python manages memory on a private heap. CPython implements small object allocation optimizations (pymalloc) and memory pools for speed.

Reference counting

Every object has a reference count. When refs drop to zero, the object is immediately deallocated.

# Simple refcount concept (illustrative only)
a = [1,2,3]
b = a   # refcount increases
b = None # refcount decreases

Cyclic garbage collector

Reference counting alone can't free cyclic references. CPython's gc module periodically detects and collects unreachable cycles.

import gc
gc.collect()

OOP & Inheritance

Types of inheritance

  • Single: One parent.
  • Multiple: Multiple parents — MRO resolves method lookup.
  • Multilevel: Parent → Child → Grandchild.
  • Hierarchical: One parent, many children.
  • Hybrid: Mix of above.

Access modifiers

Python uses naming conventions: _protected (convention) and __private (name‑mangled) — not strict enforcement.

Shallow vs Deep copy

Shallow copy duplicates outer container but shares nested objects. Deep copy recursively copies everything.

import copy
orig = [[1],[2]]
sh = copy.copy(orig)
dp = copy.deepcopy(orig)

Core Data Structures & Utilities

List vs Tuple

Lists are mutable, tuples are immutable. Tuples can be slightly faster and used as keys in dicts if immutable elements.

Slicing

Slicing extracts subsequences: seq[start:stop:step]. Negative steps reverse sequences.

zip(), range()

zip() pairs elements from iterables. range() (Python 3) is a lazy sequence object; in Python 2, xrange() provided laziness.

Pandas in brief

Pandas provides Series and DataFrame for tabular data manipulation, CSV/Excel/SQL IO, grouping, time-series utilities.

Concurrency & Parallelism

GIL (Global Interpreter Lock)

CPython's GIL allows one native thread to execute Python bytecode at a time. Threads are good for I/O‑bound workloads; use multiprocessing for CPU‑bound parallelism.

Multithreading

import threading

def worker():
    print('working')

thread = threading.Thread(target=worker)
thread.start()

Async & Fast I/O

Use async/await for non‑blocking I/O (e.g., network servers or async DB drivers). FastAPI leverages async for high throughput.

Django — MVT, ORM, Middleware, Security & DRF

MVT (Model, View, Template)

Model defines DB schema via Django ORM. View handles request/response. Template renders UI.

Models & Relationships

Define fields with ORM types and relationships using OneToOneField, ForeignKey (many‑to‑one), and ManyToManyField.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Student(models.Model):
    courses = models.ManyToManyField(Course)

Middlewares

Middleware components process requests/responses globally. Examples: security, sessions, CSRF.

CSRF protection

Django includes CSRF middleware and token helpers. In templates use {% csrf_token %} inside POST forms; middleware validates tokens.

Django ORM

ORM transforms Pythonic queries to SQL. Common patterns: .objects.create(), .filter(), .aggregate(), .select_related(), .prefetch_related().

Django REST Framework (DRF)

DRF provides serializers, ViewSets, routers, authentication and browsable API for building REST APIs.

Serializers

Serializers convert model instances to primitive types (JSON) and validate input. Example with ModelSerializer:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

Context in templates

Context is a dict passed from view to template (render(request, 'tpl.html', context)) and used as variables in templates.

Migrations

Django uses built‑in migrations (makemigrations, migrate) to evolve schema. For Flask, Alembic is commonly used (Flask‑Migrate wrapper).

Flask — Microframework Essentials

What is Flask?

Flask is a lightweight web framework providing routing, templating (Jinja2), and extension‑friendly architecture. Ideal for microservices and APIs.

Blueprints

Blueprints organize apps into components (auth, admin, api). Register blueprints on the main app instance.

auth = Blueprint('auth', __name__)
@app.register_blueprint(auth)

Decorators & Routes

Flask uses route decorators to bind URLs to view functions: @app.route('/') .

Jinja2 Templating

Jinja2 provides expressions, control‑flow, and template inheritance. Use render_template() to pass context.

Database Migrations

Flask‑Migrate (Alembic) handles migrations. Typical commands: flask db init, flask db migrate, flask db upgrade.

FastAPI — Modern, Fast APIs

What is FastAPI?

FastAPI is an async‑friendly web framework that uses Python type hints and Pydantic models for validation and automatic OpenAPI docs. It runs on ASGI servers like Uvicorn or Hypercorn.

Type hints & Pydantic

Type hints declare input & output types. Pydantic models validate and parse data automatically.

from pydantic import BaseModel
class Item(BaseModel):
    name: str
    price: float

@app.post('/items')
def create_item(item: Item):
    return item

Async endpoints

Define async def endpoints to await async I/O operations, achieving high throughput.

Validation & Auto‑docs

FastAPI exposes auto‑generated Swagger UI and Redoc; invalid inputs return detailed 422 errors from Pydantic.

© 2025 Praful Kumar. All rights reserved.