Skip to main content

Senior Python Interview Questions

Curated Senior-level Python interview questions for developers targeting senior positions. 20 questions available.

Last updated:

Python Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of Python interview questions and answers. This page contains expertly curated interview questions covering all aspects of Python, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our Python interview questions are designed to help you:

  • Understand core concepts and best practices in Python
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next Python interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic Python concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

20 questions
Q1:

What are the main Python web frameworks and their use cases?

Senior

Answer

Flask: Lightweight and flexible, ideal for microservices.
Django: Full-featured framework with ORM, admin, and authentication.
FastAPI: High-performance async API framework.
Pyramid/Tornado: Used for scalable or asynchronous workloads.
Quick Summary: Python web frameworks: Django (full-stack, batteries-included, ORM, admin, auth - for full web apps), Flask (micro-framework, flexible, choose your own components - for APIs and small apps), FastAPI (modern, async, auto-generates OpenAPI docs, Pydantic validation - for high-performance APIs), Tornado (async, websockets). FastAPI is the fastest growing choice for new REST APIs.
Q2:

How does Flask handle routing and requests?

Senior

Answer

Routes map URLs to Python functions.
Decorators define endpoint behavior.
Request/response objects manage headers, parameters, and bodies.
Quick Summary: Flask routing: @app.route("/users/") decorates a function. Supports methods parameter: methods=["GET", "POST"]. URL converters: , , , . request object provides form data, JSON body (request.get_json()), headers, files. Response: return jsonify(data), return render_template(), or return Response object with custom status.
Q3:

How does Django handle URL routing?

Senior

Answer

URL patterns map URLs to views.
Supports dynamic parameters, namespaces, and reverse resolution.
Maintains separation of logic and presentation.
Quick Summary: Django URL routing: define URL patterns in urls.py: path("users//", views.user_detail). Include app URLs in project urls.py: include("users.urls"). Named URLs: path(..., name="user-detail") allows reverse lookup: reverse("user-detail", kwargs={"pk": 1}). Class-based views have as_view(). URL patterns are matched top-to-bottom; first match wins.
Q4:

What is the difference between function-based and class-based views in Django?

Senior

Answer

Function-based views: simple and direct.
Class-based views: reusable patterns, mixins, and structured handling of HTTP methods.
Quick Summary: Function-based views (FBV): simple Python functions receiving request, returning response. Easy to understand, explicit flow. Class-based views (CBV): inherit from generic views (ListView, DetailView, CreateView), less code for standard CRUD operations, mixins for reusability. FBV: better for custom or complex logic. CBV: better for standard CRUD where Django generic views save significant boilerplate.
Q5:

How do Python frameworks handle templates?

Senior

Answer

Templates separate business logic from UI.
Use engines like Jinja2 or Django Template Language.
Support inheritance, loops, conditions, and reusable components.
Quick Summary: Django templates: {{ variable }} for output, {% tag %} for logic ({% if %}, {% for %}). Template inheritance: {% extends "base.html" %} and {% block content %}. Template filters: {{ value|lower|truncatewords:10 }}. Jinja2 is the default in Flask (and optional in Django). FastAPI uses Jinja2. Templates auto-escape HTML to prevent XSS. Always use template engine rather than string concatenation for HTML.
Q6:

How do you handle forms and input validation?

Senior

Answer

Form libraries parse, validate, and sanitize input.
Flask uses WTForms; Django has built-in forms with validation rules.
Protects against invalid and malicious input.
Quick Summary: Django forms: Form class with field types (CharField, EmailField, IntegerField) and validators. is_valid() runs validation. cleaned_data provides sanitized values. ModelForm auto-generates form from a Model. Flask-WTF adds CSRF protection and WTForms to Flask. FastAPI uses Pydantic models for request validation with automatic type coercion and error messages.
Q7:

How do you implement authentication and authorization?

Senior

Answer

Authentication verifies identity; authorization controls access.
Use sessions, JWTs, OAuth, or framework built-ins.
Django provides full authentication system; Flask uses extensions.
Quick Summary: Django auth: built-in User model, login/logout views, @login_required decorator, permission system. JWT for APIs: use djangorestframework-simplejwt. Flask: Flask-Login for session management, Flask-JWT-Extended for JWT. FastAPI: OAuth2PasswordBearer scheme with JWT. Pattern: on login, issue short-lived JWT + refresh token, validate JWT on each request without DB lookup.
Q8:

How do you build REST APIs in Python frameworks?

Senior

Answer

Map CRUD operations to HTTP verbs.
Use serializers for JSON conversion.
Follow REST principles like statelessness, versioning, and proper endpoint design.
Quick Summary: REST APIs in Python: Django REST Framework (DRF) adds serializers, viewsets, routers, authentication to Django. Flask-RESTful or Flask-RESTX for Flask. FastAPI has native REST support with Pydantic models for validation and auto-generated OpenAPI docs. Key concepts: serializers/schemas validate and convert data, viewsets provide CRUD operations, routers generate URL patterns automatically.
Q9:

How do you handle database access with ORM?

Senior

Answer

ORM maps classes to database tables.
Django ORM and SQLAlchemy handle queries, joins, and relationships.
Supports migrations and validation.
Quick Summary: Django ORM: define models as Python classes, create with model.save() or Model.objects.create(). Query: Model.objects.filter(age__gt=18).order_by("name")[:10]. Relationships: ForeignKey, ManyToManyField, OneToOneField. select_related() for JOIN queries (prevents N+1). prefetch_related() for M2M. SQLAlchemy: more flexible, works with any framework, explicit session management.
Q10:

How do you perform database migrations?

Senior

Answer

Migrations track schema changes.
Auto-generated scripts modify tables and fields.
Keep environments consistent across dev, staging, and production.
Quick Summary: Django migrations: python manage.py makemigrations (generates migration files from model changes), python manage.py migrate (applies to DB). Migrations track schema changes in version control. SQLAlchemy uses Alembic for migrations: alembic revision --autogenerate, alembic upgrade head. Always review auto-generated migrations before applying. Back up production DB before running migrations.
Q11:

How do you implement caching in web applications?

Senior

Answer

Caching reduces database load and speeds responses.
Use Redis or Memcached.
Supports page, fragment, and function-level caching.
Quick Summary: Caching in web apps: Django cache framework supports Memcached, Redis, file, database backends. @cache_page(60*15) caches a view response for 15 min. cache.get()/set() for granular caching. Redis is the standard choice (fast, distributed, TTL support). Cache DB query results, expensive computations, session data. Invalidate cache on data changes. CDN caches static files at the edge.
Q12:

How do you implement logging for web applications?

Senior

Answer

Log request context, errors, and performance metrics.
Integrate with monitoring tools.
Helps diagnose issues and maintain observability.
Quick Summary: Web app logging: use Python logging module configured with handlers. Log every request with timing. Log errors with full traceback. Structured logging (JSON) works with centralized log services (ELK, Datadog). In Django: LOGGING setting configures handlers and loggers. gunicorn/uwsgi pass logs to stdout for container environments. Include request ID in all log entries for tracing.
Q13:

How do you secure Python web applications?

Senior

Answer

Mitigate XSS, CSRF, SQL injection, and other attacks.
Use HTTPS, secure cookies, and proper session handling.
Rely on framework security middleware.
Quick Summary: Python web security: CSRF protection (Django includes this, use csrf_token in forms). SQL injection: always use ORM or parameterized queries. XSS: template engines auto-escape (don't use mark_safe() with user input). Authentication: use Django auth or established JWT libraries. HTTPS only. Keep dependencies updated (pip-audit checks for CVEs). Rate limiting on login endpoints. CORS configuration.
Q14:

How do you handle REST API versioning?

Senior

Answer

Use URL-based (/v1/), header-based, or media-type versioning.
Ensures backward compatibility as APIs evolve.
Quick Summary: REST API versioning strategies: URI versioning (/api/v1/, /api/v2/) - most common, visible in URLs. Header versioning (Accept: application/vnd.api.v2+json) - cleaner URLs. Query parameter (?version=2) - easy but pollutes URLs. DRF supports namespace versioning, URL-based versioning. Run old and new versions simultaneously during transition. Deprecate with Sunset header.
Q15:

How do you implement pagination, filtering, and sorting in APIs?

Senior

Answer

Pagination splits large data sets.
Filtering uses query parameters.
Sorting results ensures consistent ordering and performance.
Quick Summary: DRF pagination: PageNumberPagination, LimitOffsetPagination, CursorPagination. Filtering: django-filter library with DjangoFilterBackend. Search: SearchFilter on specific fields. Ordering: OrderingFilter allows clients to sort. FastAPI uses Query parameters with Depends() for pagination. Implement cursor-based pagination for large datasets (stable under insertions) instead of offset-based.
Q16:

How do you test Python web applications?

Senior

Answer

Unit tests for logic, integration tests for endpoints.
Use framework test clients to simulate requests.
Mock external dependencies.
Quick Summary: Python web testing: pytest + pytest-django or pytest-flask. Django TestCase uses a test database (auto-rollback per test). APIClient (DRF) or test_client() for HTTP testing. Mock external services with unittest.mock or responses library. Factory Boy for test data fixtures. Locust or k6 for load testing. Selenium/Playwright for end-to-end browser testing.
Q17:

How do you handle file uploads and downloads?

Senior

Answer

Validate file types and sizes.
Store files securely.
Use streaming for large downloads.
CDNs improve performance.
Quick Summary: File uploads: Django: request.FILES, FileField/ImageField model fields. Validate file size and type. Store: locally (FileSystemStorage), S3 (django-storages with boto3). Flask: request.files, werkzeug.secure_filename() to sanitize filenames. FastAPI: UploadFile type. Always validate MIME type server-side (not just extension). Downloads: StreamingResponse for large files to avoid memory issues.
Q18:

How do you implement middleware in Python frameworks?

Senior

Answer

Middleware intercepts requests and responses.
Used for logging, authentication, caching, error handling.
Stackable for modular behavior.
Quick Summary: Django middleware: MIDDLEWARE list in settings.py. Each middleware is a class with process_request and/or process_response methods. Process order: request goes top-to-bottom, response goes bottom-to-top. Common uses: authentication, CORS headers, request logging, rate limiting, compression. Flask: @app.before_request and @app.after_request decorators for simpler middleware. WSGI middleware wraps the entire application.
Q19:

How do you handle asynchronous tasks in web frameworks?

Senior

Answer

Use Celery or RQ for background tasks.
Async endpoints prevent blocking.
Improves responsiveness for heavy workloads.
Quick Summary: Async tasks in web frameworks: Celery is the standard for background task queues (Redis or RabbitMQ as broker). Django-Q and Huey are lighter alternatives. FastAPI: BackgroundTasks for quick tasks, Celery for heavyweight. Pattern: API returns immediately with a task ID, client polls for result. Use for: email sending, image processing, PDF generation, long-running computations.
Q20:

How do you deploy Python web applications?

Senior

Answer

Use WSGI servers (Gunicorn, uWSGI) or ASGI servers (Uvicorn, Daphne).
Reverse proxy with Nginx.
Containerize with Docker and automate via CI/CD.
Quick Summary: Python web deployment: containerize with Docker (Dockerfile: FROM python, pip install, CMD gunicorn). Run with gunicorn (WSGI) or uvicorn (ASGI). Nginx as reverse proxy and static file server. Docker Compose for local dev with DB. Kubernetes for production scaling. Cloud: AWS Elastic Beanstalk, GCP App Engine, Heroku, Railway. Always use environment variables for config, never hardcode secrets.

Curated Sets for Python

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice