Python Programming Questions
Python as an interview language: core syntax, data types and built-in collections, comprehensions, iterators and generators, idiomatic style, and the standard library, extending into data-oriented and automation use of the language and its common libraries. Covers writing correct, Pythonic code and reasoning about the language's semantics. The most heavily exercised language surface in this category across engineering and data roles.
Implement a safe file-based lock in Python usable across processes on the same machine. The API should support acquire(timeout) and release, and avoid race conditions if two processes try to create the lock simultaneously. Discuss platform differences (Unix vs Windows).
Sample Answer
Approach summary
Use an atomic filesystem operation to create a lockfile and store owner PID. "Atomic" here means the operating system guarantees that checking whether the file already exists and creating it happen as a single, indivisible step: the kernel resolves any race internally, so it is impossible for two processes to both be told "it didn't exist, you just created it" for the same file. Concretely, os.open(path, O_CREAT|O_EXCL) either creates the file and returns a valid file descriptor (this process is now the owner), or, if the file already exists, raises OSError with errno.EEXIST and creates nothing, there is no window in between where a second process could sneak in and also succeed. On Unix use os.open with O_EXCL|O_CREAT; on Windows use msvcrt.locking or CreateFile with exclusive flags. Implement acquire(timeout) with retries and stale-lock detection via PID and age.
Implementation (Unix-first, cross-platform fallback)
import os, time, errno
from pathlib import Path
class FileLock:
def __init__(self, path):
self.path = Path(path)
def acquire(self, timeout=10):
end = time.time()+timeout
while time.time()<end:
try:
fd = os.open(self.path, os.O_CREAT|os.O_EXCL|os.O_WRONLY)
os.write(fd, str(os.getpid()).encode())
os.close(fd)
return True
except OSError as e:
if e.errno!=errno.EEXIST: raise
time.sleep(0.1)
return False
def release(self):
try: self.path.unlink()
except FileNotFoundError: pass
Worked trace: two processes racing to acquire the same lock, simulated in one process for illustration (the real guarantee comes from the OS's atomic O_CREAT|O_EXCL, not from anything special in this simulation, but the sequence of return values is exactly what would happen with two real, separate processes):
lock_a = FileLock("/tmp/demo.lock")
lock_b = FileLock("/tmp/demo.lock")
print(lock_a.acquire(timeout=1)) # True: lock_a's os.open call wins the race, file now exists
print(lock_b.acquire(timeout=0.3)) # False: lock_b's os.open calls all hit EEXIST and it
# gives up once the 0.3s timeout elapses
lock_a.release()
print(lock_b.acquire(timeout=1)) # True: now that lock_a released (deleted the file),
# lock_b's next os.open call succeeds
The first acquire call's os.open(..., O_CREAT|O_EXCL) either wins outright (file did not exist, now it does, True) or loses outright (EEXIST, False after retries time out); there is no third outcome where both processes believe they created the file, which is exactly the race the atomic system call rules out by construction.
Platform notes
- Unix: O_EXCL is atomic across processes. Use fcntl.flock for advisory locks (a lock that only stops other processes if they also choose to check for it before touching the file; unlike a mandatory, OS-enforced lock, the OS itself does not block a process that simply ignores the lock and opens the file directly) when needed.
- Windows: O_EXCL behaves differently; prefer msvcrt.locking or pywin32 CreateFile for exclusive access.
Stale locks
Check PID from file and whether process exists; remove stale if safe. For production, add jitter, robust error handling, and optional directory-level locking for network filesystems.
Explain dependency management approaches for Python: requirements.txt with pip, pip-tools, Pipenv, Poetry, and Conda. For a reproducible data-science project, which would you pick and why?
Sample Answer
Overview of approaches:
- requirements.txt + pip: Simple, exact package names; use pip freeze to pin. Reproducible only if you pin hashes (pip hash or requirements with hashes).
- pip-tools (pip-compile): Maintains human-editable top-level requirements.in and generates fully pinned requirements.txt (including sub-deps).
- Pipenv: Combines virtualenv + Pipfile/Pipfile.lock (a lock file records the exact version, and a hash, of every package actually installed, including indirect dependencies pulled in by your direct ones, so a second install reproduces the identical environment instead of silently picking up newer, still-technically-compatible versions); locking for reproducibility but has had stability/performance issues historically.
- Poetry: Modern tool for dependency resolution, pyproject.toml, and lock file; good for packaging and reproducible installs across environments.
- Conda: Manages packages and binaries (C libs) and environments; best when native dependencies (numpy, scipy) are needed.
Which of these is baseline knowledge versus niche: for most purposes, pip + a lockfile-pinned requirements.txt and Poetry are the two worth knowing well; pip-tools and Pipenv are reasonable alternatives worth recognizing as "another lockfile-based tool" rather than needing a strong independent opinion on; Conda (and micromamba, below) only becomes necessary once native, non-Python dependencies enter the picture.
My pick for reproducible data-science project: Poetry + Conda hybrid depending on needs.
- If heavy native deps: use Conda to create base env (python, BLAS, the compiled linear-algebra library numpy/scipy rely on internally for fast matrix math, and something Poetry itself cannot install since it only manages Python-level packages, not compiled system libraries), then Poetry for Python deps inside that env, or use micromamba (a faster, lighter-weight, drop-in alternative to the
condacommand line tool, installing from the same package channels) + poetry. Concretely:conda create -n proj python=3.12 numpy scipyto get the compiled base right, thenpoetry initandpoetry add pandasinside that environment to layer the pure-Python dependencies on top with a proper lockfile. Poetry gives clear lockfile, semantic project layout, and reproducible installs. pip-tools is a lighter alternative if you prefer pip. Ensure CI records exact lockfile and Python version.
Given a Pandas DataFrame with columns 'timestamp' (timezone-aware) and 'value', write code to resample to hourly bins in UTC, forward-fill missing values, and ensure the result preserves timezone awareness and dtype. Explain pitfalls around DST transitions.
Sample Answer
Goal: resample timezone-aware timestamps to hourly UTC bins, forward-fill, preserve tz-aware dtype.
Code:
import pandas as pd
def resample_hourly_utc(df):
# ensure tz-aware
ts = pd.to_datetime(df['timestamp'])
if ts.dt.tz is None:
raise ValueError('timestamp must be timezone-aware')
# convert to UTC
df = df.copy()
df['timestamp'] = ts.dt.tz_convert('UTC')
df = df.set_index('timestamp').sort_index()
# resample hourly and forward-fill
out = df.resample('h').ffill() # lowercase 'h': pandas removed the uppercase hour alias
# ensure index tz-aware and dtype preserved
out.index = out.index.tz_localize(None).tz_localize('UTC') if out.index.tz is None else out.index
return out
Worked example, verified with pandas on CPython 3.12:
df = pd.DataFrame({
"timestamp": pd.to_datetime(
["2024-11-03 04:15", "2024-11-03 06:40", "2024-11-03 08:05"]
).tz_localize("America/New_York"),
"value": [10, 20, 30],
})
print(resample_hourly_utc(df))
Output:
value
timestamp
2024-11-03 09:00:00+00:00 NaN
2024-11-03 10:00:00+00:00 10.0
2024-11-03 11:00:00+00:00 10.0
2024-11-03 12:00:00+00:00 20.0
2024-11-03 13:00:00+00:00 20.0
The three original local readings, converted internally to UTC before resampling, become five hourly UTC bins: the first bin has no data yet before the first real reading, so it stays NaN (nothing earlier to forward-fill from), and each later hour repeats the most recent value until a newer one arrives (10.0 covers two consecutive bins because the next real reading does not land until the following hour).
DST pitfalls
- Convert to UTC before resampling to avoid ambiguous/missing local times.
- If you must resample in local tz, handle ambiguous times with tz_localize(ambiguous=...) and nonexistent with nonexistent=...; otherwise conversions across DST will produce duplicate or missing hours.
Why DST actually produces duplicate or missing local hours, made concrete: on 2024-11-03, US Eastern clocks "fall back" from 2:00 AM EDT to 1:00 AM EST, so local wall-clock time 01:00-01:59 happens twice, once while still on EDT (UTC-4) and once on EST (UTC-5):
naive = pd.Timestamp("2024-11-03 01:30:00")
first = naive.tz_localize("America/New_York", ambiguous=True) # earlier occurrence, still EDT
second = naive.tz_localize("America/New_York", ambiguous=False) # later occurrence, now EST
print(first, "->", first.tz_convert("UTC"))
print(second, "->", second.tz_convert("UTC"))
Output:
2024-11-03 01:30:00-04:00 -> 2024-11-03 05:30:00+00:00
2024-11-03 01:30:00-05:00 -> 2024-11-03 06:30:00+00:00
Both print the identical local wall-clock string, 01:30:00, but they are genuinely different instants, one hour apart in UTC; without ambiguous=, pandas has no way to know which of the two real moments a bare "2024-11-03 01:30:00" local string refers to, and that unresolved ambiguity is the "duplicate hour" pitfall.
The mirror case, a nonexistent time: on 2025-03-09, US Eastern clocks "spring forward" from 2:00 AM directly to 3:00 AM, so the entire local hour 02:00-02:59 never occurs at all:
try:
pd.Timestamp("2025-03-09 02:30:00").tz_localize("America/New_York") # expected: 02:30 never happened locally that day
except ValueError as e:
print(f'raises as expected: ValueError: {e}')
print(pd.Timestamp("2025-03-09 02:30:00").tz_localize("America/New_York", nonexistent="shift_forward"))
# 2025-03-09 03:00:00-04:00
Asking for 02:30 local time on that date raises by default, since no such wall-clock moment ever happened; nonexistent="shift_forward" is one explicit policy for handling it (push the timestamp forward past the gap), rather than silently guessing what was meant.
This approach keeps data consistent for ETL and downstream aggregation.
You're given a function that intermittently raises MemoryError when processing large NumPy arrays. List a systematic debugging and mitigation plan: how to collect memory profiles, common causes, and code changes to reduce peak memory usage.
Sample Answer
Plan: collect profiles, identify roots, mitigate with code/data changes.
Collecting memory profiles:
- Use tracemalloc (a built-in module that records which line of code allocated each block of memory, and lets you snapshot total/peak Python-level allocations at any point) for Python allocations
- Use memory_profiler (@profile) (a decorator-driven tool that reports memory usage line by line for a decorated function, run via
python -m memory_profiler script.py) to trace per-line memory - Use psutil / top for process-level peaks (
psutil: a library that reads OS-level process stats, including RSS, resident set size, the actual physical RAM a process is currently using, directly from the operating system) - For NumPy, use objgraph (a tool for visualizing and counting live Python object references, useful for finding what is unexpectedly still holding a reference to something large) / np.ndarray.nbytes sampling
- Take periodic heap dumps and track peak RSS
Which to reach for first: tracemalloc is the default starting point for almost any Python-level memory investigation, cheap to turn on, built in, and line-level. psutil/RSS is the next check when the growth seems to be happening outside pure Python objects entirely (a C extension, or a numpy allocation that tracemalloc's Python-object view does not fully capture). memory_profiler and objgraph are for harder follow-up cases once the first two have narrowed down roughly where the growth is, not where most investigations should start.
A worked trace with tracemalloc, verified on CPython 3.12 with numpy: creating a float64 array and then converting it with .astype(np.float32) (a common, easy-to-miss source of an avoidable extra allocation) shows up as two distinct, measurable jumps:
import tracemalloc
import numpy as np
tracemalloc.start()
baseline, _ = tracemalloc.get_traced_memory()
a = np.zeros(1_000_000, dtype=np.float64)
after_a, _ = tracemalloc.get_traced_memory()
b = a.astype(np.float32) # a full, avoidable copy if a float32 array was all that was ever needed
after_b, _ = tracemalloc.get_traced_memory()
print("a allocation bytes:", after_a - baseline)
print("b (astype copy) allocation bytes:", after_b - after_a)
Output:
a allocation bytes: 8000496
b (astype copy) allocation bytes: 4000096
The dominant numbers, 8,000,000 and 4,000,000, are exactly 1_000_000 * 8 bytes (float64) and 1_000_000 * 4 bytes (float32); the small remainder (496 and 96 bytes) is bookkeeping overhead from numpy's own array object and can vary slightly by numpy version, the part worth remembering is the dtype-size arithmetic, not the exact overhead constant. If a was only ever needed as float32, allocating it directly as np.zeros(1_000_000, dtype=np.float32) avoids the second, redundant 4,000,000-byte allocation entirely, this is exactly the kind of concrete before/after number a real profiling pass surfaces that a purely descriptive plan does not.
Common causes:
- Creating many temporaries (slicing / copying)
- Unnecessary copies from dtype promotion (dtype promotion: when an operation combines two arrays of different dtypes, e.g.
float32andfloat64, numpy silently produces a result in the wider of the two dtypes,float64, which can quietly double the memory of a computation that was only ever intended to stay infloat32) - Holding references to large arrays (accumulators, list append)
- Parallel workers duplicating memory
Mitigations:
- Use in-place operations (out=...) and views (a view: a new array object that points at the same underlying memory as another array, e.g.
a[::2], versus a copy, which allocates and fills an entirely separate block of memory) where safe - Use appropriate dtypes (float32 vs float64)
- Process data in chunks / streaming
- Reuse preallocated arrays and buffer pools
- Avoid building large Python lists; use arrays or write to disk-backed arrays (memmap)
- Release references and call gc.collect when necessary for deterministic release
Validation: write microbenchmarks for peak RSS (RSS: resident set size, the actual physical memory a process currently occupies, as reported by the OS), compare before/after; run under production-like data sizes.
Write a pytest unit test (in Python) for a function normalize_email(email: str) that lowercases the domain part and strips whitespace, leaving the local part unchanged except trimming. Include tests for edge cases: leading/trailing whitespace, uppercase domain, empty string, and invalid type.
Sample Answer
Pytest unit tests for normalize_email(email: str)
import pytest
from yourmodule import normalize_email
def test_strip_whitespace_and_lower_domain():
assert normalize_email(' User+tag@EXAMPLE.COM ') == 'User+tag@example.com'
def test_empty_string():
assert normalize_email('') == ''
def test_trim_local_only():
assert normalize_email(' local @DoMain.Com') == 'local@domain.com'
def test_invalid_type_raises():
with pytest.raises(TypeError):
normalize_email(None)
Notes: tests cover leading/trailing whitespace, uppercase domain, empty string, and invalid type. Adjust expected behavior if function normalizes tags or lowercases local part.
Unlock Full Question Bank
Get access to all 46 Python Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.