Skip to the solution
EasyDSA12 min read

What is the difference between a module and a package?

939 views

The problem

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 .py file, loaded into a module object 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 like shop.payments.card walk down packages
  • __init__.py runs 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__.py wins over namespace portions
  • Modules and packages are code-organisation units; a distribution (what pip install downloads) 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.

  • modules
  • packages

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonBuild a module and a package on disk, then import them
PythonNamespace packages, which package wins, and __all__

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 11 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What does if __name__ == "__main__" do?

Continue