Module Basics
How It Works A string on the first logical line of a function is the docstring for that function. Note that DocStrings also apply to modules and classes which we will learn about in the respective chapters.
Why Modules Matter
You have already learned how to reuse code within a single program by defining functions once and calling them multiple times. But what happens when you finish a program and later want to use some of those functions in a completely different program? Copying and pasting code between files is error-prone and makes maintenance a nightmare. Modules solve this problem by letting you package functions and variables into a reusable file that any program can import and use.
A module is simply a Python file with a .py extension that contains functions, variables, and other code. Instead of rewriting the same functions in every program that needs them, you write them once in a module, then import that module into any program that needs access to those functions. This is the foundation of code reuse in Python and the basis for how Python's standard library and third-party packages work.
What Makes a Module
The simplest way to create a module is to create a .py file that contains functions and variables. That file, by virtue of being a .py file, is a module. There is no special syntax required—any Python file is automatically a module.
A module is not a special Python construct; it is just a regular Python file. The .py extension is what makes it a module.
When you create a module file, you typically include functions that perform related tasks, along with any helper variables or constants those functions need. For example, you might create a module called math_helpers.py that contains functions for calculating areas, volumes, and other geometric properties. Later, any other Python program can import math_helpers and use those functions without rewriting them.
Module Docstrings
Just as functions can have docstrings that describe what they do, modules can have docstrings too. A module docstring is a string that appears on the first logical line of the module file. It describes the purpose of the entire module and what functions or variables it provides.
The first logical line of a file is the first line of actual Python code, excluding blank lines and comments that appear before any executable statement. A module docstring must be a string literal on this first logical line.
Docstrings are not the same as regular strings. When a string appears as the first statement in a module, function, or class, Python treats it as a docstring—a piece of metadata that documents the code. This docstring is stored as part of the code object and can be accessed later using the __doc__ attribute. A regular string that appears elsewhere in your code is just a string value that gets evaluated and discarded.
Building a Simple Module
Let's build a concrete example. Imagine you frequently need to perform temperature conversions in your programs. Instead of rewriting the conversion logic each time, you create a module file called temperature.py that contains functions for converting between Celsius and Fahrenheit.
This file is now a module. Notice the structure: the module docstring appears on the first logical line, describing the module's purpose. Below that are function definitions, each with its own docstring. The module also contains variables (the absolute zero constants) that can be imported and used by other programs.
How Modules Enable Code Reuse
Once you have created the temperature.py module, any other Python program can import it and use its functions. You do not have to rewrite the conversion logic; you simply import the module and call its functions. This is the power of modules: write once, use everywhere.
20°C is 68.0°F
Absolute zero: -273.15°CUnderstanding First Logical Line
When determining what counts as the first logical line of a module, you must exclude comments and blank lines that appear before any executable code. This is important because you might have a file header comment or blank lines at the top of your file, and those should not interfere with the module docstring.
In this example, the comments and blank lines at the top are ignored when determining the first logical line. The docstring is the first executable statement, so it becomes the module docstring. If you placed a regular string or any other code before the docstring, that code would execute first, and the docstring would no longer be recognized as the module docstring.
Common Mistakes with Modules
Placing the module docstring after an import statement
The first logical line is the import statement, not the string. The string becomes a regular statement that is evaluated and discarded.
Fix:
Place the docstring before any imports: """Module docstring.""" import sysConfusing a module docstring with a regular string
A docstring must be the first statement in a module, function, or class. If it is assigned to a variable or appears elsewhere, it is just a regular string.
Fix:
Place the string as the first statement without assignment: """This is a docstring."""Creating a module file without any docstring
While technically valid, a module without a docstring lacks documentation about its purpose, making it harder for others (or your future self) to understand what the module does.
Fix:
Add a module docstring at the top: """Helper functions for calculations.""" def helper(): return 42
Modules and Scope
When you create a module, remember that the functions and variables you define in it become part of that module's namespace. When another program imports your module, it accesses those functions and variables through the module name. This separation of namespaces is one of the key benefits of modules: it prevents naming conflicts and keeps code organized.
Docstrings in modules serve as the primary documentation for what the module provides. When someone (or you, months later) needs to understand what a module does, the module docstring is the first place they will look. This is why writing clear, informative docstrings is a best practice.
Practice: Create Your First Module
Create a module file called string_tools.py that contains at least two functions for manipulating strings. For example, you might include a function that reverses a string and another that counts vowels. Include a module docstring that describes what the module does, and include docstrings for each function. Then, in a separate Python script, import your module and test both functions.
Hints
- Remember to place the module docstring as the first statement in the file.
- Each function should have its own docstring describing what it does.
- Use descriptive function names that make it clear what each function does.
- Test your module by importing it in a separate script and calling each function with different inputs.
Summary
A module is a Python file with a .py extension that contains functions, variables, and other code. Modules enable code reuse: write functions once in a module, then import and use them in any program that needs them. A module docstring is a string that appears on the first logical line of the module file and describes the module's purpose. Docstrings are distinct from regular strings because Python treats them as metadata about the code. When creating modules, place the docstring before any imports, use descriptive names, and write clear docstrings that explain what the module provides. This foundation of modules is essential to understanding how Python's standard library and third-party packages work.
Key Takeaways
- A module is a .py file containing functions and variables that can be imported and reused in other programs.
- A module docstring is a string on the first logical line of a module file that describes the module's purpose and is stored as metadata, not evaluated as regular code.
- The first logical line excludes comments and blank lines; it is the first executable statement in the file.
- Modules solve the code reuse problem by allowing you to write functions once and use them in multiple programs without copying and pasting.
- Clear module and function docstrings are essential for documenting what a module provides and making your code maintainable.