Python Middle interview questions and answers

75 questions for a Python (Middle) interview - with correct answers, explanations and links to the docs.

  1. 1.What does yield turn a function into?
  2. 2.What does this code print?
  3. 3.Why is sum(x * x for x in range(10**7)) lighter on memory than sum([x * x for x in range(10**7)])?
  4. 4.Which methods make an object an iterator?
  5. 5.What does yield from other_gen() do?
  6. 6.What is a decorator?
  7. 7.Why use functools.wraps inside a decorator?
  8. 8.How is a decorator with arguments, like @retry(times=3), built?
  9. 9.What does this code print?
  10. 10.What does @functools.lru_cache do?
  11. 11.What does functools.partial(pow, exp=2) return?
  12. 12.Which methods does an object need to work with the with statement?
  13. 13.What happens if __exit__ returns True?
  14. 14.What does @contextlib.contextmanager let you write?
  15. 15.How do you give a dataclass field a fresh empty list for each instance?
  16. 16.What does @dataclass(frozen=True) give you?
  17. 17.What does __slots__ do in a class?
  18. 18.What does @property let you do?
  19. 19.What is the difference between @classmethod and @staticmethod?
  20. 20.What determines which parent method super() calls with multiple inheritance?
  21. 21.What does inheriting from abc.ABC with an @abstractmethod achieve?
  22. 22.What is a typing.Protocol for?
  23. 23.What happens at runtime when you call def f(x: int) with f("hello")?
  24. 24.How do you annotate a value that may be a str or None in modern Python?
  25. 25.When is typing.TypedDict a good fit?
  26. 26.If a class defines __eq__ but not __hash__, what happens?
  27. 27.What does collections.defaultdict(list) do on a missing key?
  28. 28.What does Counter("banana").most_common(1) return?
  29. 29.Why use collections.deque for a queue instead of a list?
  30. 30.What does heapq provide?
  31. 31.Why must data be sorted before itertools.groupby?
  32. 32.Python's sorted is stable. What does that mean?
  33. 33.What does the walrus operator := do?
  34. 34.What does the * mean in def connect(host, *, timeout=10):?
  35. 35.What does / mean in def f(a, b, /, c):?
  36. 36.What does {**a, **b} produce for two dicts?
  37. 37.What does the GIL in CPython prevent?
  38. 38.Which tool fits CPU-heavy pure Python work on a standard CPython build?
  39. 39.What does ThreadPoolExecutor.map suit best?
  40. 40.What does await do inside an async def function?
  41. 41.What happens if you call time.sleep(5) inside a coroutine?
  42. 42.What does asyncio.gather(a(), b(), c()) do?
  43. 43.What does calling a coroutine function without await do?
  44. 44.What is asyncio.run(main()) for?
  45. 45.What is a pytest fixture?
  46. 46.What does scope="session" on a pytest fixture mean?
  47. 47.What does @pytest.mark.parametrize do?
  48. 48.In app/service.py, from app.client import fetch is used. What should a test patch?
  49. 49.What is pytest's monkeypatch fixture good for?
  50. 50.Why use logging instead of print in an application?
  51. 51.What is the recommended way to get a logger in a module?
  52. 52.Why write logger.info("user %s", user_id) instead of an f-string?
  53. 53.What does raise NewError(...) from err do?
  54. 54.What should custom exceptions in an application usually inherit from?
  55. 55.What does this function return?
  56. 56.What causes an ImportError with "partially initialized module"?
  57. 57.What does __all__ in a module control?
  58. 58.What is pyproject.toml for?
  59. 59.Why commit a lock file like uv.lock for an application?
  60. 60.What does f"{total=}" print when total = 42?
  61. 61.Why is a is b unreliable for comparing integers?
  62. 62.What does an Enum member compare equal to?
  63. 63.What is the problem with datetime.now() without arguments in a backend?
  64. 64.Why does json.dumps({"at": datetime.now()}) fail?
  65. 65.What is the default timeout in requests.get(url)?
  66. 66.In FastAPI, what does declaring a parameter as a Pydantic model give you?
  67. 67.What does Depends() do in FastAPI?
  68. 68.In FastAPI, a route uses a blocking DB driver. How should it be declared?
  69. 69.What causes the N+1 query problem in the Django ORM?
  70. 70.When should you use prefetch_related rather than select_related in Django?
  71. 71.When does a Django QuerySet actually hit the database?
  72. 72.What does copy.deepcopy do with an object that references itself?
  73. 73.Why is "".join(parts) preferred over s += part in a long loop?
  74. 74.What does @pytest.fixture(autouse=True) do?
  75. 75.What should __eq__ return when it gets an object of an unsupported type?