liveBook · Manning

Directory structure

As explained in Python Workout, Second Edition

A directory is a filesystem container that organizes files and other directories under a name.

In Python, a directory becomes a package when it contains one or more Python modules. For example, placing first.py, second.py, and third.py in mypackage groups them for import. section 9.9

Use the directory structure to choose an import style:

  • Import a module directly with from mypackage import first, then access attributes as first.x. section 9.9
  • Import through the full package name with import mypackage.first, then use mypackage.first.x. section 9.9
  • Add __init__.py when importing mypackage itself; Python loads and executes that file. section 9.9

A small package directory

mypackage/ __init__.py first.py second.py third.py With the directory available through sys.path, Python can locate mypackage.first and import its contents. section 9.9

from mypackage import first

Explore the direct module-import form for a package directory. section 9.9

How Python Workout, Second Edition covers it

How deep it goes
Explains package layout, import forms, sys.path, and __init__.py, while stopping short of filesystem operations.
Examples
Uses mypackage with first.py, second.py, third.py, and __init__.py to demonstrate alternative import paths.
What you can do after
Apply it via Python imports to group modules and access them through short or fully qualified names.
How it connects
Connects directories with modules, packages, imports, sys.path, and __init__.py.

Also explained in

Compare how 7 books explain directory structure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.