150+ Python Interview Questions for DevOps (2027)
155 Python interview questions with answers for DevOps roles: freshers, 2-5 years, senior and coding scenarios, with boto3, pytest and asyncio code.
The Python questions DevOps interviewers ask most cover core data types, functions and exceptions for freshers; generators, decorators, subprocess, logging, requests, boto3 and pytest for mid-level roles; and memory, concurrency, security and service design for senior roles. This guide answers 155 distinct questions, grouped by level, with runnable code.
This post is part of our DevOps interview questions hub. It is the broad Python question bank: language basics through senior design. If you want longer production incidents to talk through, read our scenario-based Python interview questions, and for working automation examples see 10 Python scripts for DevOps automation. Version-specific details here were checked against the official Python documentation and AWS SDK documentation in November 2026.
Key takeaways
- Freshers are tested on mutability, data structures, exceptions, functions and basic OOP. Short, precise answers with a one-line example score best.
- Mid-level rounds focus on automation you have actually written: subprocess, logging, API calls with timeouts and retries, boto3 pagination, the Kubernetes client and pytest.
- Senior rounds test design judgement: idempotency, concurrency model choice, supply-chain security, observability and graceful shutdown.
- Know the GIL story accurately: an optional free-threaded build arrived experimentally in 3.13 and became officially supported in 3.14, but the default build still has the GIL.
- Security mistakes such as
shell=Truewith user input,verify=False,pickleon untrusted data and logged secrets come up often. Be ready to explain the safer option. - For coding questions, state complexity and then mention the idiomatic standard library alternative.
How the questions are organised
| Section | Questions | Typical role | What interviewers check |
|---|---|---|---|
| Freshers | 1 to 55 | Trainee, junior DevOps, support engineer | Language basics, data structures, files, OOP |
| 2 to 5 years | 56 to 105 | DevOps, cloud, SRE engineer | Automation, APIs, AWS and Kubernetes SDKs, testing, packaging |
| Senior | 106 to 130 | Senior DevOps, platform, SRE lead | Memory, concurrency, security, observability, design |
| Scenarios and coding | 131 to 155 | All levels | Debugging approach, trade-offs, live coding |
Python interview questions for freshers
Core language questions asked in first-round screens for DevOps, cloud and junior developer roles. Answer in two or three sentences and add a one-line example when you can.
1. What is Python and why do DevOps teams use it?
Python is an interpreted, dynamically typed, general-purpose language with a large standard library. DevOps teams use it because it ships on most Linux distributions, reads clearly, and has mature SDKs for clouds and tools (boto3 for AWS, the official Kubernetes client, Ansible itself is written in Python), so one language covers glue scripts, APIs and tests.
2. Is Python compiled or interpreted?
Both, in a sense. CPython compiles source to bytecode (.pyc files cached in __pycache__) and then runs that bytecode on a virtual machine. There is no separate ahead-of-time compile step you run yourself, so people call it interpreted.
3. What is the difference between Python 2 and Python 3?
Python 2 reached end of life on 1 January 2020 and gets no fixes. Python 3 made print a function, made str Unicode by default with a separate bytes type, changed integer division so / returns a float and // floors, and turned many list-returning functions such as range and dict.keys into lazy views or iterators. All new code should target a supported Python 3 release.
4. What are Python's built-in data types?
The common ones are int, float, complex, bool, str, bytes, list, tuple, range, dict, set, frozenset and NoneType. In interviews, group them by mutability: lists, dicts and sets are mutable; ints, floats, strings, tuples and frozensets are immutable.
5. What is the difference between a list and a tuple?
A list is mutable and is meant for a changing collection of similar items. A tuple is immutable, slightly cheaper to create, and hashable when all its items are hashable, so it can be a dict key or set member. Use a tuple for fixed records such as (host, port).
6. How do a dict and a set differ?
Both are hash tables with average O(1) lookups. A dict maps keys to values; a set stores only unique keys. Since Python 3.7, dicts keep insertion order as a language guarantee. Sets do not promise any order.
7. What does mutable versus immutable mean, and why does it matter?
A mutable object can change in place (list.append), while an immutable one cannot, so any 'change' creates a new object. It matters for dict keys, which must be hashable, and for shared references: two names pointing at the same list both see a change.
8. What is the difference between == and is?
== compares values by calling __eq__. is checks whether two names point to the same object. Use is only for singletons such as None (if x is None), never to compare strings or numbers.
9. How does indentation work in Python?
Indentation defines blocks instead of braces. PEP 8 recommends four spaces per level. Mixing tabs and spaces inconsistently raises TabError in Python 3.
10. What is PEP 8?
PEP 8 is the official style guide for Python code: naming (snake_case for functions, CapWords for classes), line length, imports, whitespace. Tools such as Ruff, Flake8 and Black check or apply it automatically in CI.
11. What are *args and **kwargs?
*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. They are handy for wrappers and decorators that pass arguments through to another function.
def run(cmd, *args, **kwargs):
print(cmd, args, kwargs)
run("deploy", "web", region="ap-south-1")
# deploy ('web',) {'region': 'ap-south-1'}
12. Why is a mutable default argument a bug?
Default values are evaluated once, when the function is defined. A default list or dict is therefore shared across calls and keeps growing. Use None as the default and create the object inside the function.
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
13. What is a list comprehension?
A compact expression that builds a list from an iterable with an optional filter, for example [h for h in hosts if h.endswith('.prod')]. Dict and set comprehensions use {}. Keep them short; a loop is clearer once logic needs several branches.
14. What is the difference between a list comprehension and a generator expression?
A list comprehension builds the whole list in memory. A generator expression, written with parentheses, yields items one at a time, so sum(len(l) for l in open('app.log')) can process a large file without loading it.
15. What is slicing?
Slicing extracts part of a sequence with seq[start:stop:step]. stop is exclusive, negative indexes count from the end, and s[::-1] reverses a sequence. Slicing a list returns a new shallow copy.
16. How do you handle exceptions in Python?
Wrap risky code in try, catch specific exceptions in except, put success-only code in else, and cleanup in finally. Catch the narrowest exception you can handle; a bare except: also swallows KeyboardInterrupt and hides bugs.
try:
with open(path) as f:
cfg = f.read()
except FileNotFoundError:
cfg = DEFAULT_CONFIG
else:
print("loaded", path)
finally:
print("done")
17. How do you raise a custom exception?
Subclass Exception (or a more specific built-in) and raise it with a clear message. Custom exceptions let callers catch your error types without catching everything.
class DeployError(Exception):
pass
raise DeployError("health check failed for web-01")
18. What does the with statement do?
It uses a context manager to set up and tear down a resource. For files, with open(...) closes the file even if an exception happens. Locks, database connections and temporary directories follow the same pattern.
19. How do you read a file line by line?
Iterate over the file object. It reads lazily, so memory stays flat even for multi-gigabyte logs.
with open("/var/log/app.log", encoding="utf-8") as f:
for line in f:
if "ERROR" in line:
print(line.rstrip())
20. What is the difference between a module and a package?
A module is a single .py file. A package is a directory of modules, usually with an __init__.py, that you import with dotted names such as mytool.aws.ec2.
21. What does if __name__ == "__main__": do?
When a file runs as a script, __name__ is "__main__"; when it is imported, __name__ is the module name. The guard lets a file expose functions for import and still run a main() when executed directly.
22. What is a virtual environment and why use one?
A virtual environment is an isolated directory with its own interpreter link and installed packages. It stops one project's dependencies from clashing with another's or with the system Python that OS tools rely on.
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
23. What is pip?
pip is the standard installer for packages from the Python Package Index (PyPI) or other indexes. pip install, pip freeze and pip install -r requirements.txt are the commands you will use most.
24. What is the difference between append and extend?
append(x) adds x as one element. extend(iterable) adds each element of the iterable. [1].append([2,3]) gives [1, [2, 3]]; extend gives [1, 2, 3].
25. How do you remove duplicates from a list while keeping order?
Use list(dict.fromkeys(items)). Dicts keep insertion order, so the first occurrence of each item wins. list(set(items)) also removes duplicates but loses order.
26. What are lambda functions?
A lambda is a small anonymous function limited to one expression, such as sorted(pods, key=lambda p: p['restarts']). For anything longer, a named def is easier to test and read.
27. What do map, filter and zip return?
In Python 3 they return lazy iterators, not lists. zip pairs items from several iterables and stops at the shortest; zip(strict=True) (3.10+) raises if lengths differ.
28. How does enumerate help?
enumerate(seq, start=1) yields (index, item) pairs, which removes manual counter variables in loops.
29. What is string formatting with f-strings?
f-strings (Python 3.6+) embed expressions inside f"...", for example f"{host}:{port}". They support format specs (f"{pct:.1f}%") and the debugging form f"{value=}" from 3.8. Python 3.12 (PEP 701) relaxed the grammar so you can reuse the same quote type inside the braces.
30. How do you convert between str and bytes?
Call s.encode("utf-8") to get bytes and b.decode("utf-8") to get text. Network sockets and subprocess output without text=True give bytes, which trips up many scripts.
31. What are truthy and falsy values?
Falsy values are None, False, zero of any numeric type, and empty containers ('', [], {}, set()). Everything else is truthy, so if hosts: checks for a non-empty list.
32. What is the difference between break, continue and pass?
break exits the loop, continue skips to the next iteration, and pass does nothing and acts as a placeholder where syntax needs a statement.
33. What is the for ... else construct?
The else block of a loop runs only if the loop finished without break. It is a clean way to write 'search, and act if not found'.
34. How do you sort a list of dictionaries by a key?
Use sorted(items, key=lambda d: d["cpu"], reverse=True) or operator.itemgetter("cpu"). sorted returns a new list; list.sort() sorts in place and returns None.
35. What is the difference between a shallow and a deep copy?
A shallow copy (list(x), x.copy(), copy.copy) creates a new outer container but shares nested objects. copy.deepcopy copies nested objects recursively, which you need before changing a nested config dict.
36. What are Python's scopes (LEGB)?
Name lookup goes Local, Enclosing function, Global (module), then Built-in. Use global to rebind a module variable inside a function and nonlocal to rebind an enclosing function's variable. Both are signs to consider a class or return values instead.
37. What is a docstring?
A string literal as the first statement in a module, class or function. Tools such as help(), Sphinx and IDEs read it. Describe what the function does, its arguments and what it returns or raises.
38. What are type hints?
Annotations such as def scale(n: int) -> list[str]: that document expected types. Python does not enforce them at runtime; checkers like mypy or Pyright do, usually in CI.
39. What is None?
None is the single instance of NoneType and means 'no value'. Functions without a return return None. Compare with is None.
40. How do you take command-line arguments?
For anything beyond one argument use argparse from the standard library. It gives help text, types, defaults and errors for free. sys.argv is the raw list.
import argparse
p = argparse.ArgumentParser(description="Scale a deployment")
p.add_argument("name")
p.add_argument("--replicas", type=int, default=2)
args = p.parse_args()
print(args.name, args.replicas)
41. How do you read environment variables?
Use os.environ["KEY"] when the variable is required (it raises KeyError if missing) and os.environ.get("KEY", "default") when it is optional. Pipelines often pass secrets this way, so never print them.
42. How do you work with file paths portably?
Use pathlib.Path. It joins paths with /, has methods such as exists(), glob(), read_text() and mkdir(parents=True, exist_ok=True), and works the same on Linux and Windows.
43. How do you parse JSON in Python?
json.loads parses a string and json.load reads from a file object; json.dumps/json.dump write. JSON objects become dicts and arrays become lists.
import json
with open("config.json") as f:
cfg = json.load(f)
print(json.dumps(cfg, indent=2, sort_keys=True))
44. How do you read YAML files?
YAML is not in the standard library; install PyYAML and always use yaml.safe_load, which only builds plain Python types. Plain yaml.load with an unsafe loader can construct arbitrary objects from untrusted input.
45. What is a class and an object?
A class is a blueprint that bundles data (attributes) and behaviour (methods). An object is an instance of that class. __init__ runs when you create an instance and sets its initial state.
46. What is self?
self is the conventional name for the instance passed as the first argument to instance methods. Python passes it automatically when you call obj.method().
47. What are the four pillars of OOP in Python?
Encapsulation (bundle state and methods, with _name signalling internal use), inheritance (a class reuses another with class Child(Parent)), polymorphism (different classes answer the same method call), and abstraction (hide details behind an interface, often with abc.ABC).
48. What is the difference between __str__ and __repr__?
__repr__ should give an unambiguous developer-facing representation, ideally one that could recreate the object. __str__ gives a readable form for users. print uses __str__ and falls back to __repr__.
49. What are instance, class and static methods?
Instance methods receive self. @classmethod methods receive the class as cls and are often used as alternative constructors such as Config.from_file(). @staticmethod methods receive neither and are plain functions grouped in the class.
50. What is a dataclass?
@dataclasses.dataclass generates __init__, __repr__ and __eq__ from annotated fields. It is a short way to define record types such as a Server(name: str, ip: str, port: int = 22).
51. How do you check the type of an object?
Prefer isinstance(x, (int, float)), which respects inheritance. type(x) is int ignores subclasses and is rarely what you want.
52. What is the difference between range in Python 3 and a list?
range is a lazy sequence object that stores only start, stop and step, so range(10**9) uses almost no memory. It supports indexing, len and membership tests.
53. How do you merge two dictionaries?
Python 3.9+ supports merged = a | b, where values from b win, and a |= b updates in place. {**a, **b} works on older versions.
54. What does collections.Counter do?
It counts hashable items. Counter(status_codes).most_common(5) gives the five most frequent HTTP codes from a parsed log in one line.
55. What is defaultdict?
A dict subclass that creates a default value for missing keys, for example defaultdict(list) to group log lines by host without checking whether the key exists first.
Python interview questions for 2 to 5 years of experience
These questions test whether you have written real automation: concurrency, subprocess, logging, APIs, AWS and Kubernetes SDKs, testing and packaging.
56. What is a generator and when would you use one?
A generator is a function that uses yield to produce values lazily, keeping its state between calls. Use one to stream large files, paginated API results or log lines so memory stays constant.
def errors(path):
with open(path) as f:
for line in f:
if " ERROR " in line:
yield line
for e in errors("/var/log/app.log"):
print(e, end="")
57. What is the difference between an iterable and an iterator?
An iterable can return an iterator via iter() (lists, dicts, files). An iterator has __next__, remembers its position and is consumed once. A list can be looped many times; a generator cannot.
58. What does yield from do?
It delegates to a sub-generator and passes its values through, which flattens nested generators and forwards send() and exceptions correctly.
59. What is a decorator?
A decorator is a callable that takes a function and returns a new function, usually to add behaviour such as timing, retries, logging or auth checks. Use functools.wraps so the wrapper keeps the original name and docstring.
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*a, **kw):
t = time.perf_counter()
try:
return fn(*a, **kw)
finally:
print(f"{fn.__name__} took {time.perf_counter() - t:.2f}s")
return wrapper
60. How would you write a retry decorator with exponential backoff?
Loop up to a maximum number of attempts, catch only the transient exception types, sleep for a growing delay with some jitter, and re-raise after the last attempt. Libraries such as tenacity do this well, but interviewers often want to see it by hand.
import functools, random, time
def retry(exc=(ConnectionError,), tries=5, base=0.5):
def deco(fn):
@functools.wraps(fn)
def wrapper(*a, **kw):
for attempt in range(1, tries + 1):
try:
return fn(*a, **kw)
except exc:
if attempt == tries:
raise
time.sleep(base * 2 ** (attempt - 1) + random.random() * 0.1)
return wrapper
return deco
61. What is a closure?
A closure is an inner function that remembers variables from the enclosing function after that function returns. Decorators and factory functions rely on closures.
62. How do you write your own context manager?
Either define a class with __enter__ and __exit__, or decorate a generator with contextlib.contextmanager and yield once between setup and teardown.
from contextlib import contextmanager
import os
@contextmanager
def cd(path):
old = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old)
63. What is the GIL?
The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time. Threads still help for I/O-bound work because the lock is released while waiting on I/O, but CPU-bound work needs multiprocessing or native extensions. Python 3.13 added an experimental free-threaded build without the GIL (PEP 703), and Python 3.14 moved that build to officially supported status (PEP 779). The default build still has the GIL.
64. When do you use threading, multiprocessing or asyncio?
Threading suits blocking I/O with a modest number of tasks, such as calling 20 APIs. Multiprocessing suits CPU-heavy work because each process has its own interpreter. asyncio suits thousands of concurrent network operations in a single thread when the libraries you use are async-aware.
65. How does concurrent.futures simplify concurrency?
ThreadPoolExecutor and ProcessPoolExecutor share one API: submit callables, get futures, collect results with as_completed. It is the quickest way to parallelise a loop of SSH checks or HTTP calls.
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
def status(url):
return url, requests.get(url, timeout=5).status_code
with ThreadPoolExecutor(max_workers=10) as pool:
futures = [pool.submit(status, u) for u in urls]
for f in as_completed(futures):
print(*f.result())
66. Explain async and await.
An async def function returns a coroutine. await pauses it until an awaitable finishes, letting the event loop run other coroutines meanwhile. asyncio.run(main()) starts the loop, and asyncio.gather runs several coroutines concurrently. Blocking calls such as time.sleep or requests.get stall the whole loop, so use async libraries (for example httpx or aiohttp) or asyncio.to_thread.
67. How do you run a shell command from Python safely?
Use subprocess.run with a list of arguments, check=True to raise on non-zero exit, capture_output=True, text=True to get strings, and a timeout. Avoid shell=True with any user-controlled input because it opens shell injection.
import subprocess
r = subprocess.run(["systemctl", "is-active", "nginx"],
capture_output=True, text=True, timeout=10)
print(r.returncode, r.stdout.strip())
68. What is the difference between os.system, subprocess.call and subprocess.run?
os.system runs a string through the shell and only returns the exit status. subprocess.call is an older API that returns the exit code. subprocess.run (3.5+) is the recommended interface and returns a CompletedProcess with return code, stdout and stderr.
69. How do you set up logging properly instead of print?
Create a module logger with logging.getLogger(__name__), configure handlers and format once at the entry point, and use levels (DEBUG, INFO, WARNING, ERROR, CRITICAL). Log to stdout in containers so the platform collects it.
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger(__name__)
log.info("deploy started for %s", "web")
70. Why pass arguments to the logger instead of using an f-string?
log.debug("user %s", uid) formats the message only if the level is enabled, and log aggregators can group identical templates. An f-string is always formatted, even when the message is dropped.
71. How do you produce JSON logs for ELK or Loki?
Write a logging.Formatter subclass that returns json.dumps of the record fields, or use a library such as python-json-logger or structlog. Structured fields (service, trace_id, status) make searching in Kibana or Grafana much easier than free text.
72. How do you call a REST API with requests?
Use a requests.Session for connection reuse, always set a timeout, call raise_for_status(), and parse with .json(). Without a timeout, a hung server can block a pipeline forever.
import requests
s = requests.Session()
s.headers["Authorization"] = f"Bearer {token}"
r = s.get("https://api.github.com/repos/OWNER/REPO/pulls", timeout=10)
r.raise_for_status()
print(len(r.json()))
73. How do you handle API pagination?
Loop until the API stops returning a next page: follow a Link header (r.links['next'] in requests), a next token in the body, or increment a page number. Wrap it in a generator so callers just iterate.
74. What is boto3 and what is the difference between a client and a resource?
boto3 is the AWS SDK for Python. A client is a low-level interface that maps one-to-one to AWS API operations and returns dicts. Resources are a higher-level object interface, but AWS has stated that no new features will be added to the resource interface, so new code usually uses clients.
75. How do you list all EC2 instances across pages with boto3?
Use a paginator so you do not miss results beyond the first page.
import boto3
ec2 = boto3.client("ec2", region_name="ap-south-1")
for page in ec2.get_paginator("describe_instances").paginate(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]):
for res in page["Reservations"]:
for i in res["Instances"]:
print(i["InstanceId"], i["InstanceType"])
76. How should a Python script get AWS credentials?
Let boto3's default credential chain find them: environment variables, shared config, SSO, or an IAM role attached to the EC2 instance, ECS task, Lambda function or EKS service account. Never hardcode access keys in code or commit them.
77. What are boto3 waiters?
Waiters poll an API until a resource reaches a state, for example ec2.get_waiter("instance_running").wait(InstanceIds=[iid]). They replace hand-written sleep loops.
78. How do you use the Kubernetes Python client?
Install the kubernetes package, load config with config.load_kube_config() locally or config.load_incluster_config() inside a pod, then call API classes such as CoreV1Api.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
for p in v1.list_namespaced_pod("default").items:
print(p.metadata.name, p.status.phase)
79. How would you interact with Docker from Python?
The Docker SDK for Python (pip install docker) talks to the Docker Engine API: docker.from_env(), then client.containers.list(), client.images.build(...) and so on. Many teams just call the docker CLI via subprocess in CI for simplicity.
80. What is pytest and why is it preferred over unittest?
pytest is a test framework that uses plain assert statements, discovers test_*.py files automatically, and has fixtures and parametrisation. unittest is in the standard library and pytest runs unittest-style tests too.
81. What are pytest fixtures?
Fixtures are functions decorated with @pytest.fixture that provide setup data or resources to tests by name. Built-ins such as tmp_path and monkeypatch cover temp files and environment patching.
import pytest
@pytest.fixture
def cfg(tmp_path):
p = tmp_path / "app.ini"
p.write_text("[app]\nport=8080\n")
return p
def test_port(cfg):
assert "8080" in cfg.read_text()
82. How do you mock an external call in tests?
Use unittest.mock.patch (or pytest's monkeypatch) to replace the function where it is looked up, then assert on calls. For boto3, the moto library fakes AWS services locally.
83. What is @pytest.mark.parametrize?
It runs one test function with several sets of inputs, so each case shows as a separate result. It is ideal for validators such as checking many hostnames or version strings.
84. How do you measure test coverage?
Use coverage.py, often through the pytest-cov plugin: pytest --cov=mypkg --cov-report=term-missing. Coverage shows untested lines; it does not prove the tests check the right behaviour.
85. What is pyproject.toml?
It is the standard configuration file for Python projects. PEP 518 defined the [build-system] table and PEP 621 the [project] metadata table. Tools such as pytest, Ruff, mypy and Black also read their settings from it.
86. How do you pin dependencies for reproducible builds?
Keep loose requirements in pyproject.toml and generate a lock file with exact versions and hashes, for example with pip-tools (pip-compile --generate-hashes), Poetry or uv. Install from the lock file in CI and Docker builds.
87. How do you package a CLI tool so it installs as a command?
Declare an entry point under [project.scripts] in pyproject.toml, such as mytool = "mytool.cli:main". After pip install . the mytool command is on PATH.
[project]
name = "mytool"
version = "0.1.0"
dependencies = ["requests>=2.31"]
[project.scripts]
mytool = "mytool.cli:main"
88. How do you parse a log file to count errors per hour?
Read line by line, extract the timestamp and level with a regex or split, and count with a Counter keyed by the hour.
import re
from collections import Counter
pat = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2} (\w+)")
per_hour = Counter()
with open("app.log") as f:
for line in f:
m = pat.match(line)
if m and m.group(2) == "ERROR":
per_hour[m.group(1)] += 1
for hour, n in sorted(per_hour.items()):
print(hour, n)
89. What is the difference between re.match, re.search and re.findall?
match checks only at the start of the string, search finds the first match anywhere, and findall returns all non-overlapping matches. Compile patterns you reuse with re.compile.
90. How do you handle dates and time zones?
Use timezone-aware datetime objects. datetime.now(timezone.utc) gives the current UTC time, and zoneinfo.ZoneInfo("Asia/Kolkata") (3.9+) handles named zones. Store and log in UTC, convert only for display. datetime.utcnow() is deprecated since 3.12 because it returns a naive value.
91. What is the walrus operator?
:= (3.8+) assigns inside an expression, for example while (chunk := f.read(8192)):. It avoids calling a function twice, but overuse hurts readability.
92. What does structural pattern matching do?
match/case (3.10+) matches values against patterns, including dict and class shapes. It works well for routing parsed events, such as different webhook payload types.
93. How do you validate configuration data?
For simple scripts, check required keys and types yourself and fail early with clear errors. For services, a library such as Pydantic validates types and gives readable messages. Fail at startup, not halfway through a deploy.
94. How do you read and write CSV files?
Use csv.DictReader and csv.DictWriter, opening files with newline="" as the docs recommend. For heavy analysis, pandas read_csv is faster to write but adds a large dependency.
95. How do you securely handle secrets in Python scripts?
Read them from environment variables injected by the CI system or from a secrets manager (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault) at runtime. Never commit them, never log them, and use the secrets module, not random, when you need to generate tokens.
96. What is __slots__?
Declaring __slots__ in a class replaces the per-instance __dict__ with fixed attribute storage, which saves memory when you create millions of small objects and prevents adding unexpected attributes.
97. What are magic (dunder) methods?
Methods such as __len__, __iter__, __getitem__, __enter__ and __eq__ let your objects work with built-in syntax and functions. Implementing __iter__ makes a class usable in a for loop.
98. What is method resolution order (MRO)?
With multiple inheritance, Python searches base classes in the order given by the C3 linearisation, visible in Cls.__mro__. super() follows the MRO, not just the direct parent.
99. What is an abstract base class?
A class that inherits from abc.ABC and marks methods with @abstractmethod. It cannot be instantiated until a subclass implements all abstract methods, which suits plugin interfaces such as a Notifier with Slack and email implementations.
100. What is duck typing?
Python cares whether an object has the methods you call, not its declared type. If it has .read(), you can treat it as a file. typing.Protocol lets type checkers express this formally.
101. How do you make a simple HTTP health-check endpoint?
For a quick internal tool, Flask or FastAPI are common. A FastAPI app with @app.get("/healthz") returning {"status": "ok"} served by uvicorn takes a few lines and works as a Kubernetes liveness probe target.
102. How do you exit a script with the right status code?
Call sys.exit(0) for success and a non-zero integer for failure. CI systems and shell && chains rely on the exit status, so a script that prints an error but exits 0 hides failures.
103. How do you work with SSH from Python?
Paramiko is the common library for SSH and SFTP. Fabric builds a task layer on top of it. Load keys from an agent or file, verify host keys, and avoid AutoAddPolicy in production because it trusts any host key.
104. What is the difference between sorted() stability and why it matters?
Python's sort is stable: items with equal keys keep their original order. That lets you sort by a secondary key first and the primary key second to get multi-level ordering.
105. How do you profile a slow Python script?
Start with python -m cProfile -s cumtime script.py to find hot functions, timeit for micro-benchmarks, and a sampling profiler such as py-spy for a running process. Measure before rewriting anything.
Advanced Python interview questions for senior engineers
Senior rounds move from syntax to design: memory, concurrency models, security, observability and how you structure code that a whole team depends on.
106. How does CPython manage memory?
CPython uses reference counting to free most objects as soon as their count hits zero, plus a cyclic garbage collector (the gc module) for reference cycles. Small objects come from a private allocator (pymalloc). Memory freed inside the process is often reused rather than returned to the OS, so RSS may not drop.
107. How would you find a memory leak in a long-running Python service?
Compare snapshots with tracemalloc (take_snapshot, compare_to) to see which lines allocate growing memory, check for unbounded caches, global lists and lingering references in closures, and watch gc.get_objects() counts. In production, track RSS over time and correlate with request patterns.
108. What are descriptors?
Objects defining __get__, __set__ or __delete__ that control attribute access on another class. property, classmethod, staticmethod and ORM fields are all built on descriptors.
109. What is a metaclass and when should you use one?
A metaclass is the class of a class; type is the default. It can modify classes at creation time, for example to register plugins. Most needs are better served by class decorators or __init_subclass__, which are simpler to read.
110. How does functools.lru_cache work, and what are its risks?
It memoises results keyed by the arguments, which must be hashable. Set maxsize to bound memory. Risks: caching mutable return values that callers then change, unbounded growth with maxsize=None, and stale data when the underlying source changes. Python 3.9 added functools.cache as an unbounded shortcut.
111. How do you design a Python CLI used by a whole platform team?
Use a structured CLI framework (argparse subcommands, Click or Typer), consistent exit codes, --dry-run and --output json flags, logging to stderr with data on stdout, config from file plus env overrides, and packaging with an entry point. Version it and publish to an internal index so pipelines pin a release.
112. How do you structure a large automation repository?
Use a src/ layout with a real package, separate pure logic from I/O so it can be unit tested, keep cloud calls behind small adapter modules, and put tests, lint and type checks in CI. Shared code becomes an internal library rather than copy-pasted scripts.
113. How would you write idempotent infrastructure scripts?
Read current state, compute the difference from desired state, and only apply changes needed. Use tags or names as stable identifiers, handle 'already exists' errors as success, and support --dry-run. Running the script twice should leave the system unchanged the second time.
114. How do you handle rate limiting from cloud APIs at scale?
Respect Retry-After headers, use exponential backoff with jitter, cap concurrency with a semaphore or worker pool size, and batch requests where the API allows it. boto3 also has configurable retry modes (standard, adaptive) through botocore.config.Config.
115. What is the difference between asyncio.gather and asyncio.TaskGroup?
TaskGroup (3.11+) provides structured concurrency: if one task fails, the others are cancelled and errors surface as an ExceptionGroup. gather keeps running remaining tasks by default unless you handle failures yourself.
116. How do you limit concurrency in asyncio?
Wrap the critical section in an asyncio.Semaphore, for example 20 concurrent HTTP calls, so you do not open thousands of sockets at once.
import asyncio, httpx
async def fetch(client, sem, url):
async with sem:
r = await client.get(url, timeout=10)
return url, r.status_code
async def main(urls):
sem = asyncio.Semaphore(20)
async with httpx.AsyncClient() as client:
return await asyncio.gather(*(fetch(client, sem, u) for u in urls))
117. How do you call blocking code from async code?
Use await asyncio.to_thread(func, *args) (3.9+) or loop.run_in_executor so the blocking call runs in a thread and does not freeze the event loop.
118. What are the trade-offs of the free-threaded CPython build?
It removes the GIL so threads can run Python code in parallel on several cores, which helps CPU-bound threaded workloads. The trade-offs are some single-thread overhead, the need for C extensions to support it, and new thread-safety bugs in code that relied on the GIL. Check that your dependencies publish free-threaded wheels before adopting it.
119. How do you make a Python service observable?
Emit structured logs, expose metrics (prometheus_client provides counters, gauges and histograms on a /metrics endpoint), and add distributed traces with the OpenTelemetry Python SDK and its auto-instrumentation for frameworks such as Flask, Django and requests.
120. How would you expose custom Prometheus metrics from a script?
Use prometheus_client. Long-running services expose an HTTP endpoint; short batch jobs push to a Pushgateway instead.
from prometheus_client import Counter, start_http_server
import time
DEPLOYS = Counter("deploys_total", "Deploys run", ["env"])
start_http_server(8000)
while True:
DEPLOYS.labels(env="prod").inc()
time.sleep(60)
121. How do you secure a Python supply chain?
Pin dependencies with hashes, install with pip install --require-hashes, scan with pip-audit or similar against known vulnerabilities, publish internal packages to a private index, and watch for typosquatted names. Build images from a minimal base and generate an SBOM in CI.
122. What are common security mistakes in Python automation?
Using shell=True with untrusted input, pickle.load or yaml.load on untrusted data, eval, disabling TLS verification with verify=False, logging secrets, and building SQL with string formatting instead of parameterised queries. Tools such as Bandit catch many of these in CI.
123. Why should you not unpickle untrusted data?
pickle can execute arbitrary code during loading by design, so a crafted payload can run commands. Use JSON or another data-only format for anything that crosses a trust boundary.
124. How do you build a small, secure Docker image for a Python app?
Use a multi-stage build: install dependencies in a builder stage, copy only the needed files into a slim runtime image, run as a non-root user, set PYTHONDONTWRITEBYTECODE=1 and PYTHONUNBUFFERED=1, and pin the base image tag.
FROM python:3.13-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
COPY --from=build /install /usr/local
WORKDIR /app
COPY src/ ./src/
RUN useradd -r appuser
USER appuser
CMD ["python", "-m", "src.main"]
125. How do you write an AWS Lambda function in Python well?
Create clients outside the handler so warm invocations reuse them, keep the handler thin, read config from environment variables, log in JSON, set sensible timeouts and memory, and package dependencies as a layer or container image. Test the handler as a normal function with fake events.
126. How do you test code that calls AWS without hitting AWS?
Use moto to mock services in-process, or botocore's Stubber to queue expected responses for a client. Keep integration tests against a real sandbox account separate and run them less often.
127. How would you design a plugin system in Python?
Define an interface with an ABC or Protocol, then discover implementations through package entry points (importlib.metadata.entry_points(group="mytool.plugins")). Each plugin is a separate installable package, so the core does not need changes.
128. How do you handle graceful shutdown in a Python worker?
Register handlers for SIGTERM (what Kubernetes sends first) with the signal module, stop accepting new work, finish or checkpoint the current job, then exit before the termination grace period ends. In asyncio, use loop.add_signal_handler on Unix.
129. How do you keep Python versions consistent across laptops, CI and containers?
Pin the version in one place (for example .python-version and requires-python in pyproject.toml), use the same version in the CI setup step and the Docker base tag, and test against the next release early. Tools such as pyenv or uv can install specific versions locally.
130. What changed in recent Python releases that matters for DevOps code?
3.11 brought large interpreter speedups, ExceptionGroup and tomllib for reading TOML. 3.12 relaxed f-string syntax (PEP 701) and removed distutils. 3.13 added the experimental free-threaded build and an improved interactive shell. 3.14 made the free-threaded build officially supported and added template strings (PEP 750) and deferred evaluation of annotations (PEP 649). Check the What's New page of each release before upgrading.
Scenario-based and coding questions
Interviewers use these to see how you reason. State your assumptions, start with the simplest working approach, then discuss trade-offs. For a deeper set of production scenarios, see our separate scenario guide linked above.
131. A cron script that worked for months suddenly takes hours. How do you investigate?
Check what changed: input size (a log or API result set that grew), a dependency upgrade, or a slow upstream. Add timing logs around each stage, run cProfile on a copy of the input, and look for O(n squared) patterns such as if x in big_list inside a loop; switching that list to a set often fixes it. Also confirm network calls have timeouts.
132. Your script fails in CI with ModuleNotFoundError but works on your laptop. What do you check?
Confirm CI installs from the same requirements or lock file, that it runs the same Python version, that the package is installed (pip install -e . or PYTHONPATH) rather than relying on your current directory, and that the import name matches the package layout. Print sys.version and pip freeze in the job to compare.
133. Write a script that finds AWS EBS volumes not attached to any instance.
Filter describe_volumes on status available, paginate, and report size and age. Report first; deletion should be a separate, reviewed step.
import boto3
ec2 = boto3.client("ec2")
pages = ec2.get_paginator("describe_volumes").paginate(
Filters=[{"Name": "status", "Values": ["available"]}])
for page in pages:
for v in page["Volumes"]:
print(v["VolumeId"], v["Size"], "GiB", v["CreateTime"].date())
134. A deployment script must roll back if the health check fails. How would you write it?
Record the current version before deploying, deploy the new one, poll the health endpoint with a timeout and backoff, and on failure redeploy the recorded version and exit non-zero so the pipeline marks the run failed. Log each step and keep the rollback path tested, not just written.
135. You need to check disk usage on 200 servers and alert on any above 85%. How?
Prefer the monitoring system already in place (node exporter plus an alert rule). If you must script it, run checks in parallel with a thread pool over SSH (Paramiko or Fabric) or through Ansible, collect results, and send one summary alert. Handle unreachable hosts as their own category.
136. A script reading a 20 GB log file runs out of memory. How do you fix it?
Stop reading the whole file (f.read() or readlines()); iterate line by line or in fixed-size chunks, aggregate counts instead of storing lines, and use generators between stages. If you need sorting or joins, process in batches or use a tool built for it.
137. Two scripts writing the same JSON state file corrupt it. What do you do?
Write to a temporary file in the same directory and os.replace it over the original, which is atomic on the same filesystem. Add a lock (fcntl.flock on Linux or a lock file) if both can run at once, or move the state to a database or object store with conditional writes.
138. Your API client gets intermittent 503 errors. How do you handle them?
Treat 502, 503 and 504 plus connection errors as retryable, retry with exponential backoff and jitter up to a limit, honour Retry-After, and log each retry. With requests, mount an HTTPAdapter with urllib3's Retry to do this at the session level. Do not retry non-idempotent POSTs blindly.
139. How would you automate rotating a secret stored in AWS Secrets Manager?
Secrets Manager supports rotation through a Lambda function that runs the create, set, test and finish steps. Write the Lambda in Python, update the target system (for example a database user) in the set step, verify in the test step, and let applications fetch the secret at runtime rather than caching it forever.
140. A Python service in Kubernetes keeps getting OOMKilled. What do you look at?
Compare the container memory limit with real usage, check for unbounded caches or per-request data kept in globals, count worker processes (each Gunicorn worker is a full copy), use tracemalloc in a staging copy, and tune limits only after you understand growth. Fewer workers with threads may fit better.
141. Write a function that validates a list of Kubernetes manifests have resource limits.
Load each YAML document with yaml.safe_load_all, walk to the pod template's containers, and report any container missing resources.limits. Wire it into CI to fail the merge request. Policy engines such as Kyverno or OPA Gatekeeper enforce the same rule at admission time.
import sys, yaml
def missing_limits(path):
with open(path) as f:
for doc in yaml.safe_load_all(f):
if not doc:
continue
spec = doc.get("spec", {})
pod = spec.get("template", {}).get("spec", spec)
for c in pod.get("containers", []):
if not c.get("resources", {}).get("limits"):
yield doc["kind"], doc["metadata"]["name"], c["name"]
bad = [m for p in sys.argv[1:] for m in missing_limits(p)]
for kind, name, c in bad:
print(f"{kind}/{name}: container {c} has no limits")
sys.exit(1 if bad else 0)
142. A teammate's script uses requests.get(url, verify=False). What do you say?
Disabling TLS verification allows man-in-the-middle attacks and hides certificate problems. Point verify at the correct CA bundle (or set REQUESTS_CA_BUNDLE) for internal CAs instead, and fix expired or mismatched certificates at the source.
143. How would you parse Nginx access logs and find the top 10 client IPs returning 5xx?
Split each line or use a regex for the combined log format, keep lines whose status starts with 5, count the first field with a Counter, and print most_common(10). For continuous use, ship the logs to ELK or Loki and query there instead.
144. A script must work on both Linux build agents and Windows developer machines. What do you watch for?
Use pathlib for paths, avoid shelling out to Unix-only tools, open files with an explicit encoding, handle line endings, and use shutil.which to find executables. Test on both in a CI matrix.
145. How would you migrate a pile of Bash scripts to Python?
Start with scripts that are long, parse data or have complex error handling, since those benefit most. Keep behaviour identical, add tests around the new version, use subprocess only for tools with no Python API, and roll out one script at a time. Simple three-line Bash wrappers can stay as Bash.
146. Your GitHub Actions job needs to post a summary of failed tests. How?
Have pytest write JUnit XML (--junitxml=report.xml), parse it with xml.etree.ElementTree, and append Markdown to the file path in the GITHUB_STEP_SUMMARY environment variable, which GitHub renders on the run page.
147. A long-running asyncio service stops responding but the process is alive. What do you suspect?
A blocking call on the event loop (sync HTTP, time.sleep, CPU-heavy parsing) or a deadlock waiting on a task that never completes. Run with PYTHONASYNCIODEBUG=1 or asyncio.run(main(), debug=True) to log slow callbacks, and use py-spy dump to see where it is stuck.
148. You must generate a daily cost report from AWS Cost Explorer. Outline the script.
Call the Cost Explorer get_cost_and_usage API through boto3 for the previous day, grouped by service or by a cost-allocation tag, convert the result to rows, write CSV or post a summary to Slack, and schedule it with EventBridge running a Lambda. Use an IAM role limited to the Cost Explorer read actions.
149. How would you stop a script from running twice at the same time on one host?
Take an exclusive non-blocking lock on a lock file with fcntl.flock (Linux) at startup and exit cleanly if the lock is held. The lock is released when the process exits, even if it crashes, unlike a PID file you forget to delete.
150. How do you prove your Python automation is safe to run in production?
Unit tests for logic, integration tests against a sandbox, a --dry-run mode that prints planned changes, idempotent behaviour, code review, least-privilege credentials, structured logs for audit, and a staged rollout starting with one environment or a small set of hosts.
151. An interviewer asks you to reverse words in a sentence without using split. How do you approach it?
Walk the string, collect characters into a word buffer until you hit a space, push each completed word onto a list, then join the list in reverse order. Explain the O(n) time and space, then mention that in real code ' '.join(s.split()[::-1]) is the clear choice.
152. Write a function to check whether a string of brackets is balanced.
Push opening brackets on a stack and pop when you see a closing one, checking they match. The string is balanced if the stack is empty at the end. Time and space are O(n).
def balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
153. Find the first non-repeating character in a string.
Count characters with a Counter in one pass, then return the first character whose count is 1 in a second pass. Two linear passes give O(n) time.
from collections import Counter
def first_unique(s):
counts = Counter(s)
return next((c for c in s if counts[c] == 1), None)
154. Merge two sorted lists into one sorted list.
Use two pointers, take the smaller head each step, then append whatever remains. This is O(n + m). In practice heapq.merge does it lazily for any number of sorted inputs.
def merge(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]
155. Given a list of numbers and a target, return indices of two numbers that add up to the target.
Store each number's index in a dict as you go; for each number check whether target - n is already in the dict. One pass, O(n) time.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = i
return None
Quick reference: concurrency choices
| Workload | Good fit | Why |
|---|---|---|
| Dozens of blocking API or SSH calls | ThreadPoolExecutor | GIL is released during I/O waits; simple API |
| Thousands of concurrent network calls | asyncio with an async client | One thread, low overhead per connection |
| CPU-heavy parsing or hashing | ProcessPoolExecutor / multiprocessing | Separate processes avoid the GIL |
| CPU-heavy threaded code on 3.14+ | Free-threaded build | Threads run in parallel if dependencies support it |
How to prepare in the last week
- Rewrite three of your own work scripts with argparse, logging, timeouts and tests. You will talk about them with confidence.
- Practise the coding questions above aloud, stating complexity before you code.
- Read the What's New pages for the last two Python releases so version questions do not surprise you.
- Review the neighbouring topics interviewers mix in: CI/CD tools, Docker interview questions and AWS DevOps interview questions.
If you want guided practice, our DevOps training in Pune includes scripting and automation labs alongside CI/CD, containers and cloud, in the Kharadi classroom or live online.
Official references
- Python 3 documentation
- What's New in Python (release notes)
- PEP 8: Style Guide for Python Code
- PEP 703: Making the GIL optional and PEP 779
- subprocess module documentation
- boto3 resources guide (feature freeze note)
- pytest documentation
- Python Packaging User Guide: pyproject.toml
Frequently asked questions
How many Python questions are in this guide?
There are 155 distinct numbered questions: 55 for freshers, 50 for 2 to 5 years of experience, 25 for senior engineers and 25 scenario and coding questions.
Which Python topics matter most for DevOps interviews?
Expect file and log parsing, subprocess, error handling, logging, REST APIs with requests, boto3 for AWS, the Kubernetes client, testing with pytest, virtual environments and packaging. Senior roles add concurrency, security and observability.
Which Python version should I prepare with?
Use a currently supported Python 3 release and know what changed recently, such as f-string changes in 3.12 and the free-threaded build introduced experimentally in 3.13. Check python.org for the current list of supported versions.
Do DevOps engineers need data structures and algorithms in Python?
Usually at a basic level. Expect string and list problems, dicts and sets for counting and lookups, and simple stack or two-pointer questions. Deep algorithm rounds are more common for software engineering roles.
Is the GIL removed in new Python versions?
Not by default. Python 3.13 added an optional free-threaded build without the GIL, and Python 3.14 made that build officially supported, but the standard build still uses the GIL.
Should I use boto3 clients or resources?
Use clients for new code. AWS has said the resource interface will not get new features, while clients map directly to every AWS API operation.
How should I practise for a Python DevOps interview?
Write small scripts that solve real tasks: parse a log, call an API with pagination and retries, list cloud resources, validate YAML in CI, and test them with pytest. Explaining code you wrote yourself is the best preparation.
Where can I learn Python automation as part of DevOps training?
Our DevOps training in Pune covers scripting and automation alongside CI/CD, containers and cloud. It runs as classroom sessions in Kharadi, Pune and as live online classes across India.
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0