liveBook · Manning

Module

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A module is a distinct, bounded software unit that groups related code or functionality and provides an organizational or interaction boundary within a larger system.

A module is a Python file whose functions can be imported and reused by other programs. Any .py file can serve as a module, even when it began as a standalone program. section 14.3.3 section 14.5

Importing a function

A rhymer.py file can expose stemmer() for interactive testing: import it with `from rhymer import stemmer`, then call `stemmer('banana')`. Alternatively, use the qualified name `rhymer.stemmer('cake')`. section 14.3.3

Use modules to keep reusable code separate from program execution:

  • Guard command-line startup with `if __name__ == '__main__': main()`, so importing the module does not run main(). section 14.3.3
  • Prefer small, tested functions in shared modules over copying code between programs; one fix can then benefit every user. section 14.3.3 section 14.5

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains importing, qualified names, and the __name__ guard, but stops short of module packaging or advanced import mechanics.
Examples
Demonstrates importing and calling stemmer() from rhymer.py in the REPL.
What it assumes
Assumes basic Python programs and functions; teaches module use through an existing .py program.
What you can do after
Apply modules by importing reusable functions and preventing command-line startup during imports.
How it connects
Connects modules with functions, testing, imports, and command-line programs.

Also explained in

Compare how 35 books explain module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.