Python Interview Preparation Guide [2025]
Prepare for 2025 Python interviews with this comprehensive Python Interview Preparation Guide [2025], featuring 100+ Python coding interview questions with solutions 2025. Covering Python interview questions for freshers 2025, Python scripting for DevOps interview questions 2025, Python OOPs interview questions and answers 2025, and Advanced Python interview questions for data science & automation 2025, it equips candidates with Python 3, Django, Pandas, NumPy, and cloud tool expertise. Master IT, AI, and DevOps interviews with practical solutions for scalable, efficient Python applications in technical roles.
![Python Interview Preparation Guide [2025]](https://www.devopstraininginstitute.com/blog/uploads/images/202509/image_870x_68bff62eec340.jpg)
Python Interview Preparation Guide [2025]
Python remains a cornerstone for software development, data science, and DevOps due to its simplicity and versatility. This guide provides 103 scenario-based questions for freshers, experienced developers, and experts, covering core Python, data structures, web frameworks, DevOps integration, and testing. It equips you with practical insights to excel in technical interviews.
Core Python Concepts
1. What is Python, and why is it widely used in 2025?
Python is an interpreted, high-level language known for readability and versatility.
- Used in web development (Flask), data science (Pandas), and automation (Ansible).
- Supports rapid prototyping and scalability.
- Large community and libraries like NumPy drive adoption.
Its simplicity accelerates development across industries.
2. How do Python’s Global Interpreter Lock (GIL) impact multithreading?
The GIL allows only one thread to execute Python bytecode at a time, limiting true parallelism in CPython.
Use multiprocessing
for CPU-bound tasks or asyncio
for I/O-bound tasks to bypass GIL limitations, improving performance in multithreaded Python applications.
3. What is the difference between a list and a tuple in Python?
- List: Mutable, defined with
[]
, e.g.,[1, 2, 3]
. Supports append/remove. - Tuple: Immutable, defined with
()
, e.g.,(1, 2, 3)
. Faster for iteration.
Use lists for dynamic data, tuples for fixed data to optimize memory in Python.
4. How do you handle exceptions in Python?
Use try
, except
, else
, and finally
blocks:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("Cleanup")
This ensures robust error handling in Python applications.
5. What are Python decorators, and how do they work?
Decorators wrap functions to modify behavior.
def log(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
The @log
decorator logs function calls, enhancing modularity in Python.
6. How do you manage memory in Python?
Python uses automatic garbage collection via reference counting and a cyclic garbage collector.
- Use
gc
module to manage cycles. - Monitor memory with
tracemalloc
.
This prevents memory leaks in large Python applications.
7. What is the difference between __str__
and __repr__
in Python?
__str__
: User-friendly string representation, e.g.,str(obj)
.__repr__
: Developer-friendly, unambiguous representation, e.g.,repr(obj)
.
class Person:
def __str__(self): return "Person"
def __repr__(self): return "Person()"
Use __str__
for readability, __repr__
for debugging.
8. How do you implement a context manager in Python?
Use with
statement or define __enter__
and __exit__
:
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
This ensures resource cleanup, like closing files, in Python.
9. What are Python’s lambda
functions, and when are they useful?
Lambda functions are anonymous, single-expression functions:
square = lambda x: x * x
Use for short, inline operations in map()
, filter()
, or sorting to simplify Python code.
10. How do you achieve concurrency in Python?
- Threading: Use
threading
for I/O-bound tasks, limited by GIL. - Multiprocessing: Use
multiprocessing
for CPU-bound tasks. - Asyncio: Use
asyncio
for asynchronous I/O.
import asyncio
async def task():
await asyncio.sleep(1)
print("Task done")
asyncio.run(task())
Choose based on task type for optimal Python performance.
11. What is the difference between ==
and is
in Python?
==
checks value equality, e.g.,[1, 2] == [1, 2]
.is
checks identity (same memory), e.g.,a is b
.
Use==
for data comparison,is
for object identity in Python.
12. How do you use list comprehensions in Python?
List comprehensions provide concise list creation:
squares = [x**2 for x in range(5)]
# Output: [0, 1, 4, 9, 16]
Use for readable, efficient data transformations in Python.
13. What are Python generators, and why are they memory-efficient?
Generators yield items one at a time using yield
:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
They avoid storing entire sequences in memory, ideal for large datasets in Python.
14. How do you handle file I/O in Python?
Use open()
with with
for safe file handling:
with open('file.txt', 'w') as f:
f.write("Hello, Python!")
This ensures files are closed properly, preventing resource leaks in Python.
15. What is the purpose of __init__
in Python classes?
__init__
initializes instance attributes:
class Car:
def __init__(self, brand):
self.brand = brand
It sets up objects during instantiation in Python.
Data Structures and Algorithms
16. How do you implement a stack in Python?
Use a list as a stack with append()
and pop()
:
stack = []
stack.append(1) # Push
stack.pop() # Pop
Lists provide efficient LIFO operations for Python stacks.
17. How do you reverse a linked list in Python?
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse_list(head):
prev, curr = None, head
while curr:
curr.next, prev, curr = prev, curr, curr.next
return prev
This reverses a linked list iteratively, optimizing space complexity in Python.
18. What is the time complexity of Python’s dictionary operations?
- Lookup, insertion, deletion: O(1) average case (hash table).
- Worst case: O(n) due to hash collisions.
Use dictionaries for fast key-value access in Python.
19. How do you implement a binary search in Python?
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Requires a sorted array, with O(log n) time complexity in Python.
20. How do you find the longest common substring in Python?
Use dynamic programming:
def lcs(str1, str2):
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_len, end = 0, 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
end = i
return str1[end-max_len:end]
This finds the longest common substring with O(m*n) time complexity.
21. How do you implement a queue in Python?
Use collections.deque
for efficient queue operations:
from collections import deque
queue = deque()
queue.append(1) # Enqueue
queue.popleft() # Dequeue
deque
provides O(1) append and pop operations for Python queues.
22. How do you detect a cycle in a linked list in Python?
Use Floyd’s cycle-finding algorithm:
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
This detects cycles with O(n) time and O(1) space in Python.
23. What is the difference between a set and a frozenset in Python?
- Set: Mutable, e.g.,
set([1, 2])
. Supports add/remove. - Frozenset: Immutable, e.g.,
frozenset([1, 2])
. Usable as dictionary keys.
Usefrozenset
for hashable collections in Python.
24. How do you implement a priority queue in Python?
Use heapq
for a min-heap-based priority queue:
import heapq
pq = []
heapq.heappush(pq, (1, "task1"))
heapq.heappop(pq) # Pop lowest priority
heapq
ensures O(log n) push/pop operations in Python.
25. How do you merge two sorted lists in Python?
def merge_sorted_lists(list1, list2):
result = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
result.extend(list1[i:])
result.extend(list2[j:])
return result
This merges lists in O(n+m) time, preserving order in Python.
26. How do you find the kth largest element in an array?
Use a min-heap with heapq
:
import heapq
def kth_largest(arr, k):
heap = arr[:k]
heapq.heapify(heap)
for num in arr[k:]:
if num > heap[0]:
heapq.heapreplace(heap, num)
return heap[0]
This finds the kth largest in O(n log k) time in Python.
27. How do you implement a trie in Python?
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
Tries enable efficient string operations like prefix search in Python.
28. How do you reverse a string in Python?
Use slicing for simplicity:
def reverse_string(s):
return s[::-1]
This reverses a string in O(n) time, leveraging Python’s slicing efficiency.
29. How do you check if a string is a palindrome?
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
This checks palindromes in O(n) time, ignoring spaces and case in Python.
30. How do you implement a depth-first search (DFS) in Python?
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited
DFS explores graphs recursively, useful for pathfinding in Python.
Web Development with Python
31. How do you build a REST API with Flask?
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def get_data():
return jsonify({"message": "Hello, Flask!"})
if __name__ == '__main__':
app.run(debug=True)
Flask enables lightweight REST APIs with JSON responses in Python.
32. How do you handle database connections in Django?
Use Django’s ORM with a database configuration:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
This abstracts database interactions, ensuring scalability in Python.
33. What is middleware in Django, and how do you create custom middleware?
Middleware processes requests/responses globally.
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print("Processing request")
response = self.get_response(request)
return response
Add to settings.py
for request logging in Django.
34. How do you handle authentication in Flask?
Use flask-jwt-extended
for JWT-based authentication:
from flask_jwt_extended import JWTManager, jwt_required
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'secret'
jwt = JWTManager(app)
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
return jsonify({"msg": "Authenticated"})
This secures Flask APIs with token-based authentication.
35. How do you optimize a Django application for performance?
- Use
select_related
for foreign keys. - Cache views with Redis.
- Enable database indexing.
- Use
gunicorn
for production.
This reduces query times and improves scalability in Python.
36. How do you implement WebSockets in Python with FastAPI?
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Connected")
await websocket.close()
FastAPI supports real-time communication for Python web apps.
37. How do you handle file uploads in Flask?
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save('uploads/' + file.filename)
return "File uploaded"
This securely handles file uploads in Flask applications.
38. How do you configure CORS in a Flask API?
Use flask-cors
:
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
This enables cross-origin requests for Flask APIs in Python.
39. How do you implement rate limiting in FastAPI?
Use fastapi-limiter
:
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
import redis.asyncio as redis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis_instance = redis.Redis(host='localhost', port=6379)
await FastAPILimiter.init(redis_instance)
@app.get("/limited")
async def limited_route():
return {"msg": "Rate-limited endpoint"}
This restricts API usage, enhancing security in Python.
40. How do you deploy a Python web app to AWS?
Use Elastic Beanstalk:
# requirements.txt
flask==2.0.1
gunicorn==20.1.0
- Create
application.py
with Flask app. - Deploy with
eb deploy
. - Monitor with CloudWatch.
This ensures scalable deployment in Python.
DevOps Integration with Python
41. How do you automate infrastructure provisioning with Python?
Use boto3
for AWS provisioning:
import boto3
ec2 = boto3.client('ec2')
response = ec2.run_instances(
ImageId='ami-12345678',
InstanceType='t2.micro',
MinCount=1,
MaxCount=1
)
This automates EC2 instance creation in Python.
42. How do you integrate Python with Jenkins for CI/CD?
Use python-jenkins
:
import jenkins
server = jenkins.Jenkins('http://localhost:8080', username='user', password='pass')
server.build_job('my-job')
This triggers Jenkins builds from Python scripts.
43. How do you use Python for log parsing in DevOps?
Use re
for log analysis:
import re
with open('app.log') as f:
errors = [line for line in f if re.search(r'ERROR', line)]
This extracts error logs efficiently in Python.
44. How do you automate Docker container management with Python?
Use docker
library:
import docker
client = docker.from_env()
client.containers.run('nginx', ports={'80/tcp': 8080})
This automates container deployment in Python.
45. How do you monitor system resources with Python?
Use psutil
:
import psutil
cpu_usage = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
print(f"CPU: {cpu_usage}%, Memory: {memory}%")
This tracks resource usage for DevOps monitoring in Python.
46. How do you use Python to interact with Kubernetes?
Use kubernetes
client:
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
This manages Kubernetes resources programmatically in Python.
47. How do you automate AWS Lambda deployments with Python?
Use boto3
:
import boto3
lambda_client = boto3.client('lambda')
with open('function.zip', 'rb') as f:
lambda_client.update_function_code(
FunctionName='myFunction',
ZipFile=f.read()
)
This automates serverless deployments in Python.
48. How do you use Python for configuration management in DevOps?
Use ansible
programmatically:
from ansible.module_utils.basic import AnsibleModule
module = AnsibleModule(argument_spec={})
module.exit_json(changed=False, msg="Configured")
This integrates Python with Ansible for DevOps automation.
49. How do you implement a Python script for health checks?
import requests
def health_check(url):
try:
response = requests.get(url)
return response.status_code == 200
except:
return False
This monitors application health in DevOps pipelines.
50. How do you use Python to parse Prometheus metrics?
Use prometheus-client
:
from prometheus_client import Gauge
gauge = Gauge('app_metrics', 'Application metrics')
gauge.set(42)
This exposes metrics for Prometheus monitoring in Python.
Testing and Debugging
51. How do you write unit tests in Python using unittest
?
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
unittest.main()
This ensures code reliability with automated tests in Python.
52. How do you use pytest
for testing Python code?
def test_add():
assert 1 + 1 == 2
Run with pytest
to execute tests and generate reports in Python.
53. How do you mock dependencies in Python tests?
Use unittest.mock
:
from unittest.mock import patch
def test_api_call():
with patch('requests.get') as mocked_get:
mocked_get.return_value.status_code = 200
assert requests.get('http://example.com').status_code == 200
This isolates dependencies for reliable testing in Python.
54. How do you debug Python code effectively?
Use pdb
:
import pdb
def buggy_function():
x = 1 / 0
pdb.set_trace()
This allows interactive debugging with breakpoints in Python.
55. How do you measure code coverage in Python?
Use coverage.py
:
coverage run -m pytest
coverage report
This tracks test coverage, ensuring thorough testing in Python.
56. How do you test asynchronous Python code?
Use pytest-asyncio
:
import pytest
import asyncio
@pytest.mark.asyncio
async def test_async_function():
await asyncio.sleep(1)
assert True
This tests async functions in Python applications.
57. How do you handle flaky tests in Python?
- Use
pytest-rerunfailures
:
pytest --reruns 5
- Isolate dependencies with mocks.
- Log test runs for analysis.
This reduces test flakiness in Python.
58. How do you perform integration testing in Python?
Use pytest
with real dependencies:
def test_db_connection():
conn = connect_to_db()
assert conn.is_active()
This validates system interactions in Python.
59. How do you use Python’s logging
module for debugging?
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Debugging info")
This logs detailed information for debugging Python applications.
60. How do you test REST APIs in Python?
Use requests
with pytest
:
import requests
def test_api():
response = requests.get('http://api.example.com')
assert response.status_code == 200
This verifies API functionality in Python.
Advanced Python Topics
61. How do you implement a metaclass in Python?
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['custom'] = True
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
Metaclasses customize class creation in Python.
62. How do you use Python’s asyncio
for concurrent programming?
import asyncio
async def main():
await asyncio.gather(
asyncio.sleep(1, result="Task1"),
asyncio.sleep(1, result="Task2")
)
asyncio.run(main())
asyncio
handles I/O-bound concurrency efficiently in Python.
63. What is Python’s dataclasses
module, and how is it used?
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
dataclasses
simplifies class definitions with automatic methods in Python.
64. How do you optimize Python code for performance?
- Use list comprehensions over loops.
- Leverage
numba
for JIT compilation. - Profile with
cProfile
. - Use
multiprocessing
for parallel tasks.
This enhances Python code efficiency.
65. How do you handle large datasets in Python?
Use pandas
for data manipulation:
import pandas as pd
df = pd.read_csv('large.csv', chunksize=1000)
for chunk in df:
process(chunk)
This processes data in chunks, optimizing memory in Python.
66. How do you implement a custom iterator in Python?
class MyRange:
def __init__(self, n):
self.i, self.n = 0, n
def __iter__(self):
return self
def __next__(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
raise StopIteration
This creates a custom iterable in Python.
67. How do you use Python’s functools
module?
Use partial
for function customization:
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
This simplifies function calls in Python.
68. How do you implement a singleton pattern in Python?
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
This ensures a single instance in Python applications.
69. How do you use Python’s multiprocessing
for parallel processing?
from multiprocessing import Pool
def square(n):
return n * n
with Pool(4) as p:
results = p.map(square, [1, 2, 3])
This parallelizes tasks, bypassing GIL in Python.
70. How do you handle memory leaks in Python?
Use tracemalloc
to track allocations:
import tracemalloc
tracemalloc.start()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
This identifies memory leaks in Python applications.
Python in Data Science
71. How do you use pandas
for data analysis?
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
mean = df['A'].mean()
pandas
simplifies data manipulation and analysis in Python.
72. How do you visualize data with matplotlib
?
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
This creates visualizations for data insights in Python.
73. How do you perform machine learning with scikit-learn
?
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3]]
y = [2, 4, 6]
model = LinearRegression().fit(X, y)
This trains a linear regression model in Python.
74. How do you handle missing data in pandas
?
import pandas as pd
df = pd.DataFrame({'A': [1, None, 3]})
df['A'].fillna(df['A'].mean(), inplace=True)
This imputes missing values, ensuring data integrity in Python.
75. How do you use numpy
for numerical computations?
import numpy as np
arr = np.array([1, 2, 3])
squared = np.square(arr)
numpy
enables efficient array operations in Python.
76. How do you perform data aggregation in pandas
?
import pandas as pd
df = pd.DataFrame({'group': ['A', 'A', 'B'], 'value': [1, 2, 3]})
grouped = df.groupby('group').sum()
This aggregates data by groups in Python.
77. How do you use seaborn
for advanced visualizations?
import seaborn as sns
sns.heatmap([[1, 2], [3, 4]])
seaborn
enhances data visualizations in Python.
78. How do you optimize pandas
for large datasets?
Use dask
for out-of-memory computation:
import dask.dataframe as dd
ddf = dd.read_csv('large.csv')
This scales pandas
operations for big data in Python.
79. How do you perform feature scaling in scikit-learn
?
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform([[1], [2], [3]])
This normalizes features for machine learning in Python.
80. How do you save and load machine learning models in Python?
Use joblib
:
from sklearn.linear_model import LinearRegression
import joblib
model = LinearRegression()
joblib.dump(model, 'model.pkl')
model = joblib.load('model.pkl')
This persists models for reuse in Python.
Python in DevOps
81. How do you automate cloud resource management with Python?
Use boto3
for AWS:
import boto3
s3 = boto3.client('s3')
s3.create_bucket(Bucket='my-bucket')
This automates S3 bucket creation in Python.
82. How do you use Python for CI/CD pipeline scripting?
Use python-jenkins
:
import jenkins
server = jenkins.Jenkins('http://localhost:8080', username='user', password='pass')
server.create_job('new-job', config_xml)
This automates Jenkins job creation in Python.
83. How do you parse JSON logs in Python?
import json
with open('logs.json') as f:
logs = json.load(f)
This extracts data from JSON logs in DevOps pipelines.
84. How do you use Python to monitor API health?
import requests
def check_api(url):
response = requests.get(url)
return response.status_code == 200
This monitors API availability in DevOps.
85. How do you automate SSH tasks with Python?
Use paramiko
:
import paramiko
client = paramiko.SSHClient()
client.connect('hostname', username='user', password='pass')
client.exec_command('ls')
This automates SSH operations in Python.
86. How do you use Python for Prometheus metrics?
from prometheus_client import Counter
counter = Counter('requests_total', 'Total requests')
counter.inc()
This exposes custom metrics for DevOps monitoring.
87. How do you automate backups with Python?
import shutil
shutil.copy('data.db', 'backup.db')
This automates file backups in DevOps.
88. How do you use Python to interact with Git?
Use gitpython
:
from git import Repo
repo = Repo('path/to/repo')
repo.git.commit('-m', 'Automated commit')
This automates Git operations in Python.
89. How do you use Python for log aggregation?
import glob
logs = []
for file in glob.glob('*.log'):
with open(file) as f:
logs.extend(f.readlines())
This aggregates logs for DevOps analysis.
90. How do you automate Kubernetes deployments with Python?
from kubernetes import client, config
config.load_kube_config()
v1 = client.AppsV1Api()
v1.create_namespaced_deployment('default', deployment)
This automates Kubernetes deployments in Python.
Advanced Scenarios
91. How do you handle race conditions in Python?
Use threading.Lock
:
from threading import Lock
lock = Lock()
def safe_increment(counter):
with lock:
counter.value += 1
This prevents race conditions in multithreaded Python apps.
92. How do you implement a thread pool in Python?
Use concurrent.futures
:
from concurrent.futures import ThreadPoolExecutor
def task(n):
return n * n
with ThreadPoolExecutor(max_workers=4) as executor:
results = executor.map(task, [1, 2, 3])
This manages thread pools efficiently in Python.
93. How do you optimize Python for high-performance computing?
Use numba
:
from numba import jit
@jit
def fast_sum(arr):
total = 0
for x in arr:
total += x
return total
numba
compiles Python to machine code for performance.
94. How do you handle large JSON files in Python?
Use ijson
for streaming:
import ijson
with open('large.json') as f:
for item in ijson.items(f, 'item'):
process(item)
This processes large JSON files memory-efficiently.
95. How do you implement a custom descriptor in Python?
class Descriptor:
def __get__(self, obj, owner):
return obj._value
def __set__(self, obj, value):
obj._value = value
Descriptors control attribute access in Python classes.
96. How do you use Python for distributed systems?
Use celery
:
from celery import Celery
app = Celery('tasks', broker='redis://localhost')
@app.task
def add(x, y):
return x + y
This distributes tasks across workers in Python.
97. How do you handle Python package dependencies?
Use pip
and requirements.txt
:
pip freeze > requirements.txt
pip install -r requirements.txt
This ensures consistent environments in Python.
98. How do you profile Python code performance?
Use cProfile
:
import cProfile
cProfile.run('my_function()')
This identifies performance bottlenecks in Python.
99. How do you implement a circuit breaker in Python?
class CircuitBreaker:
def __init__(self, max_failures, reset_timeout):
self.max_failures = max_failures
self.reset_timeout = reset_timeout
self.failures = 0
self.last_failure = 0
This prevents cascading failures in distributed Python apps.
100. How do you use Python for data streaming?
Use confluent-kafka
:
from confluent_kafka import Consumer
consumer = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'mygroup'})
consumer.subscribe(['mytopic'])
msg = consumer.poll()
This processes streaming data in Python.
101. How do you implement a rate limiter in Python?
from time import time, sleep
class RateLimiter:
def __init__(self, calls, period):
self.calls = calls
self.period = period
self.times = []
def allow(self):
now = time()
self.times = [t for t in self.times if now - t < self.period]
if len(self.times) < self.calls:
self.times.append(now)
return True
return False
This limits API calls in Python applications.
102. How do you use Python for log rotation?
Use logging.handlers
:
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('myapp')
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=5)
logger.addHandler(handler)
This manages log files in DevOps environments.
103. How do you secure Python applications?
- Use
secrets
for random tokens. - Validate inputs with
schema
. - Encrypt with
cryptography
. - Monitor with Prometheus.
This ensures secure Python applications.
Tips to Ace Python Interviews
- Master core Python with hands-on coding on LeetCode.
- Showcase projects using Flask, Django, or
pandas
to highlight practical experience. - Practice DevOps integration with
boto3
andansible
. - Discuss trends like async programming and data science libraries to show awareness.
- Use resources like Python’s official docs and PyPI for solutions.
- Communicate problem-solving clearly, blending technical depth with clarity.
What's Your Reaction?






