A module is a file containing Python code. Modules can be Python files written by you, someone else, or built-in modules. Modules contain functions, classes, and variables that can be used throughout a project. Writing modular code helps write code that's easier to maintain, grow, and manage.
Modules are added using the import statement followed by the name of the module. The name of the module is the name of the file without .py; therefore, special_operations.py is referenced as special_operations.
1import special_operations
2
3list_product = special_operations.prod([1, 2, 3])You can use from x import y syntax to only import certain elements from a module.
1from special_operations import prod, avg
2
3list_prod = prod([1, 2, 3])
4list_avg You can use import x as y to change the name of an import. This is common for longer import names or if multiple imports have the same name. Here are some of the most common import shorthands:
1import numpy as np
2import matplotlib.pyplot as plt
3import networkx as nx
4import pandas as pd
5A directory of modules is a package, and modules inside it are imported with dotted names. Consider the following directory setup:
mainfolder:
mainfile.py
subfolder1:
file1.py
subfolder2:
file2.pyFrom the directory that contains mainfolder, we can import any of these files with an absolute import:
1import mainfolder.mainfile
2import mainfolder.subfolder1.file1
3from mainfolder.subfolder2 import file2Inside the package, a module can also use a relative import (PEP 328), where a leading dot means "this package" and two dots mean "the parent package". From file1.py:
from ..subfolder2 import file2python3 file1.py directly fails with ImportError: attempted relative import with no known parent package; run it as python3 -m mainfolder.subfolder1.file1 from the top directory instead.The built-in dir() function shows what a module defines.
For example, consider the math module:
1>>> import math
2>>> dir(math)
3['__doc__', Importing a module runs it. Every top-level statement in the file executes the first time it's imported, the same as if you had run the file directly. That's what defines its functions and variables, but it also runs anything else at the top level, such as a print or the code that solves a challenge.
Say special_operations.py ends with a quick test of its own functions:
1def prod(nums):
2 result = 1
3 for n in nums:
4 result *= n
Now every file that runs import special_operations prints 6 as a side effect. To keep code from running on import, Python gives every module a variable called __name__. When a file is run directly, its __name__ is the string "__main__"; when it's imported, __name__ is the module's name. Checking it separates the two cases:
1def prod(nums):
2 result = 1
3 for n in nums:
4 result *= n
Running python3 special_operations.py still prints 6, but importing it no longer does. Most scripts follow this shape, often with the top-level work moved into a main() function:
1def main():
2 ...
3
4if __name__ == "__main__":
5A module can also be run by its import name instead of its file path, using python3 -m. This runs it with __name__ set to "__main__", and it's how you run a module inside a package, as in the relative import warning above. Many standard-library modules are useful run this way:
python3 -m http.server 8000Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...That one-liner serves the current directory over HTTP, a quick way to move files onto a target machine during a CTF.