Skip to content

Python Interview Questions for Experienced Developers (3 to 5 Years): 16 Questions With Answers

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 12 min read

PythonPython Interview QuestionsExperiencedPython DeveloperInterview Preparation
Python Interview Questions for Experienced Developers (3 to 5 Years): 16 Questions With Answers

Python interviews for experienced developers move past syntax into how the language works: generators and iterators, decorators, context managers, the GIL and Python's free-threaded build, concurrency with threads, processes and asyncio, memory management, and how you structure, type and test real code. Interviewers want to hear trade-offs, not definitions. The sixteen questions below are the ones I'd expect for a developer with three to five years of Python, with answers you can give in a minute and code you can run.

I'm Gulab Chand Tejwani from TechNet Consultancy. For experienced candidates, I've found the best signal is a simple follow-up: "When would you not use that?". Anyone can define a decorator. Fewer people can explain when a decorator makes code harder to debug. So each answer below includes the trade-off.

Language internals

1. What's the difference between an iterable, an iterator and a generator?

An iterable is anything you can loop over (it has __iter__). An iterator produces values one at a time with __next__ and remembers where it is. A generator is the easiest way to write an iterator: a function with yield that pauses and resumes.

def read_in_batches(items, size):
    for i in range(0, len(items), size):
        yield items[i:i + size]

for batch in read_in_batches(list(range(7)), 3):
    print(batch)   # [0, 1, 2] then [3, 4, 5] then [6]

Trade-off: generators save memory because they produce values lazily, but they can only be consumed once, and errors surface when values are pulled, not when the generator is created.

2. How does a decorator work? Write one.

A decorator is a function that takes a function and returns a new function, usually wrapping the original. @decorator is shorthand for func = decorator(func).

import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
    return wrapper

@timed
def total(n):
    return sum(range(n))

total(1_000_000)

Mention functools.wraps: without it, the wrapper hides the original function's name and docstring, which breaks logging and debugging. Trade-off: stacked decorators make stack traces and control flow harder to follow.

3. How would you write a decorator that takes arguments?

Add one more level: a function that returns the decorator.

def retry(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError:
                    if attempt == times:
                        raise
        return wrapper
    return decorator

@retry(times=3)
def fetch():
    ...

4. What is a context manager, and how do you write one?

An object that sets something up on entry and reliably cleans up on exit, even if an exception happens: files, locks, database transactions. Write one with a class (__enter__ / __exit__) or with contextlib.contextmanager.

from contextlib import contextmanager

@contextmanager
def transaction(conn):
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise

5. How does Python manage memory?

CPython uses reference counting: each object counts the references to it and is freed when the count reaches zero. A cyclic garbage collector finds groups of objects that only reference each other (cycles) and frees them. Interview follow-ups: weakref for caches that shouldn't keep objects alive, __slots__ to cut per-instance memory on classes with many instances, and tracemalloc to find leaks.

6. What is the MRO?

The method resolution order is the order Python searches classes for a method in multiple inheritance, computed with the C3 linearisation. Check it with ClassName.__mro__. super() follows the MRO, not just the direct parent, which is why cooperative multiple inheritance works when every class calls super().

Topics for experienced Python interviews: language internals, concurrency, design and typing, testing and tooling, recent Python versions
The five areas experienced Python interviews usually cover.

Concurrency and performance

7. What is the GIL, and does it still matter?

The Global Interpreter Lock in standard CPython lets only one thread run Python bytecode at a time. Threads still help for I/O-bound work (network calls, file reads), because a thread waiting on I/O releases the lock. For CPU-bound work, threads don't run Python code in parallel on the standard build.

What changed: CPython now has an optional free-threaded build without the GIL. It was experimental in Python 3.13 and became officially supported (still optional, not the default) in Python 3.14. Python 3.15 adds a stable ABI for free-threaded builds, which makes it easier for C extensions to support it. A strong answer says: the default build still has the GIL, some C extensions may not yet support free-threading, and single-threaded code can run a little slower on the free-threaded build.

8. Threads, processes or asyncio: which and when?

ModelBest forWatch out for
threading / ThreadPoolExecutorI/O-bound work with blocking librariesGIL limits CPU parallelism on the default build; shared state needs locks
multiprocessing / ProcessPoolExecutorCPU-bound work on the default buildProcess start-up cost; data must be pickled between processes
asyncioMany concurrent I/O tasks (thousands of connections)Needs async-aware libraries; one blocking call stalls everything
Free-threaded build + threadsCPU-bound parallel Python codeOptional build; check extension compatibility
Choosing a concurrency model in Python

9. What happens if you call a blocking function inside async code?

It blocks the event loop, so every other task waits. Use the async version of the library, or push the blocking call to a thread with asyncio.to_thread.

import asyncio
import time

def slow_report():
    time.sleep(1)          # blocking
    return "done"

async def main():
    result = await asyncio.to_thread(slow_report)
    print(result)

asyncio.run(main())

10. How do you find out why code is slow?

Measure before changing anything. cProfile (or a sampling profiler such as py-spy) to find hot functions, timeit for micro-benchmarks, tracemalloc for memory. Then fix the algorithm or data structure first (a set lookup instead of a list scan often beats any micro-optimisation), use built-ins and vectorised libraries, cache repeated work with functools.lru_cache, and only then consider concurrency or compiled extensions. Python 3.15 also adds a dedicated profiling package to the standard library.

Design, typing and testing

11. When would you use a dataclass, a NamedTuple or a plain class?

  • dataclass: records with behaviour, defaults, optional immutability (frozen=True) and slots=True.
  • NamedTuple: small immutable records that should also behave like tuples.
  • Plain class: when construction or behaviour is complex enough that generated methods get in the way.
from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Order:
    order_id: int
    amount: float
    tags: tuple[str, ...] = field(default_factory=tuple)

12. How do you use type hints in a real codebase?

Annotate public functions and data models, run a type checker (mypy or pyright) in CI, and use Protocol for structural typing so code depends on behaviour, not concrete classes. Remember that hints aren't enforced at runtime unless a library such as Pydantic validates them.

from typing import Protocol

class Notifier(Protocol):
    def send(self, to: str, message: str) -> None: ...

def alert(n: Notifier, user: str) -> None:
    n.send(user, "Your report is ready")

13. How do you test code that calls an external API?

Keep the API call behind a small interface, inject it, and replace it with a fake in unit tests (or patch it with unittest.mock). Use pytest fixtures for setup, parametrise edge cases, and keep a few integration tests against a sandbox. Interviewers listen for whether you test behaviour or implementation details.

14. What does a modern Python project setup look like?

A pyproject.toml for metadata and dependencies, a lock file for reproducible installs, a virtual environment per project, a formatter and linter (Ruff is common now), a type checker and pytest, all run in CI. Tools such as uv or Poetry manage environments and locking. Name what you've used and why.

Recent Python versions

15. What's new in Python 3.15?

Python 3.15 was released in October 2026. Features worth knowing:

  • frozendict, a built-in immutable, hashable dictionary (PEP 814).
  • Explicit lazy imports with the lazy import syntax (PEP 810), which defer loading a module until it's first used and can speed up start-up.
  • UTF-8 as the default encoding (PEP 686), so open() without an encoding argument no longer depends on the operating system's locale. That's a real fix on Windows.
  • Unpacking in comprehensions (PEP 798) and a built-in sentinel type (PEP 661).
# Python 3.15
lazy import json             # loaded only when first used

config = frozendict(env="prod", region="ap-south-1")
cache = {config: "warm"}     # hashable, so usable as a key

Don't overclaim in an interview. Most production code runs on older versions, and the honest answer is often "we're on 3.12 or 3.13, and here's what we'd gain by upgrading".

Recent Python changes: 3.13 experimental free-threaded build, 3.14 free-threading officially supported, 3.15 frozendict, lazy imports and UTF-8 default
Recent CPython changes that come up in interviews, from the official What's New pages.

16. What does a mutable default argument bug look like in production code?

The same as for freshers, just better hidden. Inside a class or a cached function, a shared default list or dict leaks data between requests. Experienced candidates should spot it in code review and explain the fix (None default, create inside) and how a linter catches it.

Practice questions

Question 1Python · Concurrency

On the standard CPython build, you need to speed up a pure-Python, CPU-heavy calculation over a large list on an 8-core machine. What is the most reliable choice?

  1. AThreadPoolExecutor
  2. Basyncio.gather
  3. CProcessPoolExecutor
  4. DA generator expression
Show answer and explanation

Correct answer: C

On the default build the GIL stops threads from running Python bytecode in parallel, and asyncio doesn't add CPU parallelism. Separate processes each have their own interpreter. On a free-threaded build, threads could be an option too.

Question 2Python · Generators

g = (x * x for x in range(3)); print(sum(g), sum(g)). What is printed?

  1. A5 5
  2. B5 0
  3. C0 0
  4. DAn error
Show answer and explanation

Correct answer: B

A generator can be consumed only once. The first sum uses up all values (0 + 1 + 4 = 5); the second gets nothing and returns 0.

Question 3Python · Decorators

After decorating a function with a wrapper that doesn't use functools.wraps, what is the most likely problem?

  1. AThe function's __name__ and docstring are replaced by the wrapper's
  2. BThe function can no longer accept keyword arguments
  3. CThe function runs twice
  4. DThe return value is lost
Show answer and explanation

Correct answer: A

Without functools.wraps, metadata like __name__, __doc__ and __wrapped__ belongs to the wrapper, which confuses logging, debugging tools and documentation.

Question 4Python · asyncio

An async web handler calls requests.get() (a blocking HTTP library). Under load, all requests slow down. What is the best fix?

  1. AIncrease the number of event loops
  2. BAdd time.sleep(0) after the call
  3. CWrap the handler in a try/except
  4. DUse an async HTTP client, or run the blocking call with asyncio.to_thread
Show answer and explanation

Correct answer: D

A blocking call stalls the single event loop. Switch to an async client, or move the call to a worker thread so the loop stays free.

How should an experienced developer prepare?

Read your own code from a year ago and explain every design choice out loud as if an interviewer asked "why?". Then practise a few timed coding problems, because experienced rounds still include one, and rusty speed is the most common reason good engineers underperform. The Python interview questions for freshers post covers the entry-level problems; experienced rounds add follow-ups on complexity and edge cases.

Python interview practice has a Python developer track with algorithm and everyday engineering exercises you solve and run in the browser, with hints, test checks and worked answers. It's 200+ questions for a one-time ₹199. If the role touches data, the pandas interview questions post covers the pandas 3.0 changes interviewers have started asking about.

FAQ

What Python questions are asked for 3 years of experience?

Generators and iterators, decorators, context managers, the GIL, threads vs processes vs asyncio, memory management, dataclasses, type hints, testing with pytest and mocking, plus a coding problem with follow-ups on complexity.

Is the GIL removed in Python 3.14?

Not from the default build. Python 3.14 officially supports an optional free-threaded build without the GIL, but the standard build still has it. Python 3.13 introduced the free-threaded build as experimental.

What is new in Python 3.15?

Released in October 2026, Python 3.15 adds a built-in frozendict, explicit lazy imports with lazy import, UTF-8 as the default encoding, unpacking in comprehensions, a sentinel built-in and a profiling package in the standard library.

What's the difference between a generator and a list comprehension?

A list comprehension builds the whole list in memory immediately. A generator expression produces values one at a time when asked, using little memory, but can only be iterated once.

Do experienced Python interviews include coding rounds?

Usually yes, often a medium-difficulty problem followed by questions about complexity, edge cases, testing and how you'd change the design for scale.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.