Python A Small Package
A package is a folder that groups modules for one job. An __init__.py file inside the folder marks it as a package.
Build the folder and the files
os.mkdir makes the toolkit folder. The two writes then put __init__.py and calc.py inside it.
import os
try:
os.mkdir("toolkit")
except FileExistsError:
pass
with open("toolkit/__init__.py", "w") as f:
f.write("")
with open("toolkit/calc.py", "w") as f:
f.write("def add(a, b):\n return a + b\n")
import toolkit.calc
print(toolkit.calc.add(3, 4))One module, two functions
The calc module now holds add and triple. Both are called through the package name.
import os
try:
os.mkdir("toolkit")
except FileExistsError:
pass
with open("toolkit/__init__.py", "w") as f:
f.write("")
with open("toolkit/calc.py", "w") as f:
f.write("def add(a, b):\n return a + b\n\ndef triple(n):\n return n * 3\n")
import toolkit.calc
print(toolkit.calc.add(3, 4))
print(toolkit.calc.triple(5))Import the module directly
from toolkit import calc brings the module in on its own. The calls then skip the package name.
import os
try:
os.mkdir("toolkit")
except FileExistsError:
pass
with open("toolkit/__init__.py", "w") as f:
f.write("")
with open("toolkit/calc.py", "w") as f:
f.write("def add(a, b):\n return a + b\n")
from toolkit import calc
print(calc.add(10, 5))Example
import os
try:
os.mkdir("shapes")
except FileExistsError:
pass
with open("shapes/__init__.py", "w") as f:
f.write("")
with open("shapes/rect.py", "w") as f:
f.write("def area(w, h):\n return w * h\n\ndef perimeter(w, h):\n return 2 * (w + h)\n")
import shapes.rect
print("Area:", shapes.rect.area(5, 3))
print("Perimeter:", shapes.rect.perimeter(5, 3))Key points
- Package: a folder that holds modules, marked by a file called __init__.py
- Use os.mkdir to make the folder, then write the files into it
- Use import package.module to bring in one module from a package
- The __init__.py file can stay empty. Its presence marks the folder as a package.
- Use package.module.function() to call a function from the package
- A package groups modules that belong to one job
In this example, the program builds a package called shapes. It makes the folder, writes an empty __init__.py, and writes rect.py with two functions. The import brings the rect module in through the package name. The two printouts show the area and the perimeter of a 5 by 3 rectangle. The folder, the marker file, and the module all played their part.
Note
The folder name must be a plain word with no spaces, like a variable name.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What marks a folder as a package?