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
- 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, wherereview_statsis the folder andtext_toolsthe file. - What happens when Python runs
import text_tools?●It finds
text_tools.py, runs it once, creates a module object, and binds the nametext_toolsto it:type(text_tools)is<class 'module'>. A secondimportin the same session finds the module already loaded and does nothing, which is why an edited module needsimportlib.reloador a restart. - What is the difference between
import math,from math import sqrtandfrom math import *?●●import mathbinds the namemath, and we writemath.sqrt.from math import sqrtbinds onlysqrt, somath.sqrt(4)then givesNameError: name 'math' is not defined.from math import *binds every public name and notmath; PEP 8 advises against it, because a reader can not see where a name came from, and it can replace names of our own. - What does
if __name__ == "__main__":do?●● - Where does Python look for a module, and what can go wrong?●●
- Is
__init__.pyrequired to make a package?●●
Environments
- What is a virtual environment, and why use one per project?●
- What is the difference between
pyproject.tomlanduv.lock?●● - How do
uv add,pip installandpython -m venvrelate?●● - Should
.venvbe committed to version control?●
Files
- Why use
with open(...) as f:?● - What do the modes
"r","w","a"and"x"do?●● - Why should every
openname an encoding?●● - What type are the values
csv.DictReadergives?●● - What changes when a Python object goes through JSON and back?●●
Exceptions
- How do you read a traceback?●
- Why is
except Exception: passa bad idea?●● - What do
elseandfinallydo in atrystatement?●● - When should a function raise an exception, and which type?●●
Debugging, testing and tools
- How do you approach a bug?●
- What does
breakpoint()do?●● - What makes a good test?●●
- How do you test that a function raises an error?●●
- What is the difference between a formatter, a linter and a type checker?●●
- If Ruff and mypy report nothing, is the code correct?●●