Sub topic 1
What a module is
Prerequisites
This chapter assumes you can write Python functions and classes, run a script from a terminal, and navigate files and directories on your computer. You do not need to know anything about packages yet.
A module is a file, and also an object
A module is a Python source file that you can load from other code. If you save a file named greet.py, Python can import it as the module greet. The module's name is the file name without the .py extension.
The file and the module are two different things:
- The file is text on disk. It holds the source code.
- The module is an object in memory. Python creates it when you import the file, and it is an instance of
types.ModuleType.
The module object has attributes. Each top-level name the file defines, such as a function, class, or variable, becomes an attribute of that object.
import math
print(type(math))
print(math.__name__)
print(math.pi)
print(callable(math.sqrt))Running this prints <class 'module'>, then math, then 3.141592653589793, then True. The name math in your code refers to a module object. pi and sqrt are attributes of that object.
Building your own module
Create a file called shapes_basic.py:
# shapes_basic.py
PI = 3.14159
def circle_area(r):
return PI * r * r
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.sideIn another file in the same directory, use it:
import shapes_basic
print(shapes_basic.PI)
print(shapes_basic.circle_area(2))
print(shapes_basic.Square(3).area())The names PI, circle_area, and Square live inside the shapes_basic module object. You reach them with dot notation. This keeps them separate from names in your own file.
Inspecting a module
Because a module is an object, you can examine it with the usual tools.
import shapes_basic
print(shapes_basic.__name__)
print(shapes_basic.__file__)
print([n for n in dir(shapes_basic) if not n.startswith("__")])The last line lists the public names: ['PI', 'Square', 'circle_area']. The __file__ attribute shows the path of the source file that produced the module.
Common errors
- ModuleNotFoundError: Python cannot find a module with that name. Check the spelling and that the file is where Python looks. Later chapters cover the search path.
- Invalid file names: A file named
my-tools.pyor2d.pycannot be imported with a plainimportstatement, because the module name must be a valid identifier. - Confusing file and name: You write
import shapes_basic, notimport shapes_basic.py. Adding.pymakes Python look for a submodule namedpy.
Exercise
You save a file named tools.py containing def double(x): return x * 2. Write the code to call double on 4 from another file in the same directory, and say what type(tools) returns after the import.
Show answer
Use import tools and then print(tools.double(4)), which prints 8. type(tools) returns <class 'module'>, because tools is a module object whose attribute double is the function.