SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
Python · Module 5Module material

Python modules and exceptions interview questions

25 questions interviewers ask on organising code, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.

Modules and packages

  1. What is the difference between a module and a package?●

    A module is one Python file that other code imports. A package is a folder of modules, imported with dotted names: from review_stats.text_tools import tokenise, where review_stats is the folder and text_tools the file.

  2. What happens when Python runs import text_tools?●

    It finds text_tools.py, runs it once, creates a module object, and binds the name text_tools to it: type(text_tools) is <class 'module'>. A second import in the same session finds the module already loaded and does nothing, which is why an edited module needs importlib.reload or a restart.

  3. What is the difference between import math, from math import sqrt and from math import *?●●

    import math binds the name math, and we write math.sqrt. from math import sqrt binds only sqrt, so math.sqrt(4) then gives NameError: name 'math' is not defined. from math import * binds every public name and not math; PEP 8 advises against it, because a reader can not see where a name came from, and it can replace names of our own.

  4. What does if __name__ == "__main__": do?●●
  5. Where does Python look for a module, and what can go wrong?●●
  6. Is __init__.py required to make a package?●●

Environments

  1. What is a virtual environment, and why use one per project?●
  2. What is the difference between pyproject.toml and uv.lock?●●
  3. How do uv add, pip install and python -m venv relate?●●
  4. Should .venv be committed to version control?●

Files

  1. Why use with open(...) as f:?●
  2. What do the modes "r", "w", "a" and "x" do?●●
  3. Why should every open name an encoding?●●
  4. What type are the values csv.DictReader gives?●●
  5. What changes when a Python object goes through JSON and back?●●

Exceptions

  1. How do you read a traceback?●
  2. Why is except Exception: pass a bad idea?●●
  3. What do else and finally do in a try statement?●●
  4. When should a function raise an exception, and which type?●●

Debugging, testing and tools

  1. How do you approach a bug?●
  2. What does breakpoint() do?●●
  3. What makes a good test?●●
  4. How do you test that a function raises an error?●●
  5. What is the difference between a formatter, a linter and a type checker?●●
  6. If Ruff and mypy report nothing, is the code correct?●●