Python Modules
A module is a Python file. A package is a folder of modules. import pulls one in.
Import forms
PYTHON
import math
print(math.pi)
from math import pi, sqrt
print(sqrt(2))
import numpy as np # aliased
from collections import (
Counter, defaultdict, OrderedDict, # bracketed grouped imports
)
Your own module
Make a file shapes.py:
PYTHON — shapes.py
PI = 3.14159
def area(r):
return PI * r * r
Then in another file in the same folder:
PYTHON
import shapes print(shapes.area(5))
Packages
A folder becomes a package if it contains __init__.py (empty is fine). Sub-folders become sub-packages:
shop/
__init__.py
customers.py
orders/
__init__.py
items.py
PYTHON
from shop.orders.items import format_total
Where Python looks
Python searches in order:
- The directory of the running script.
- Directories in
PYTHONPATH. - The standard library.
- Installed packages (
site-packages).
Tip: The
if __name__ == '__main__': idiom lets a file work as both an import and a script. Code under that line only runs when the file is executed directly.Example
Example
import math
import json
print(math.pi, math.sqrt(16))
print(json.dumps({'ok': True}))
Try it Yourself »
Exercise
Import the standard math module.
math
Six letters.
Discussion
Loading…