Question presented to candidate:
"In Python, what is the difference between a module and a package? How does Python know a folder is a package, what does __init__.py do, and is it still required?"
What a strong answer should cover:
- A module is the unit of import: usually one
.pyfile, loaded into amoduleobject whose attributes are the file's top-level names - A package is a module that can contain other modules: it has a
__path__attribute (the folders searched for its submodules), and its own code lives in__init__.py - At run time both are the same type (
types.ModuleType); "package" just means "has__path__", and dotted names likeshop.payments.cardwalk down packages __init__.pyruns once on first import and is where a package exposes its public API (re-exports,__all__); importing a package does not import all its submodules- Namespace packages (PEP 420, Python 3.3+) have no
__init__.py, can be split over several folders, and have__file__ = None; a regular package with__init__.pywins over namespace portions - Modules and packages are code-organisation units; a distribution (what
pip installdownloads) is a different thing that can ship many of them
Code / implementation expected: Optional β sketch a small folder layout and show import pkg.sub and from pkg import name.