indusai.co

Modules and packages

A module is a file of Python code you can import into another file. Splitting a program into modules keeps each file focused, and importing from the standard library or third party packages gives you thousands of ready made tools.

Importing a standard library module

python
import math
print(math.sqrt(49))
print(math.pi)

import math loads the module and makes its contents available under the name math.

Importing specific names

python
from math import sqrt, pi
print(sqrt(49), pi)

Now sqrt is available directly. Avoid from math import *; it dumps every name into your file and makes it unclear where things came from.

Aliases

python
import datetime as dt
print(dt.date.today().year)

Aliases are conventional for some libraries: import numpy as np, import pandas as pd.

Writing your own module

Any .py file is a module. Suppose helpers.py contains:

python
# helpers.py
TAX_RATE = 0.18

def with_tax(amount):
    return round(amount * (1 + TAX_RATE), 2)

A file in the same folder can use it:

python
# main.py
import helpers
print(helpers.with_tax(100))

from helpers import with_tax
print(with_tax(250))

if name == "main"

When a file is run directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name. This lets a file be both a script and an importable module.

python
def main():
    print("Running as a script")

if __name__ == "__main__":
    main()

Test code and command line entry points go under this guard so they do not run on import.

Packages

A package is a folder of modules, usually with an __init__.py file. Dots separate the levels.

output
shop/
    __init__.py
    cart.py
    payments.py
python
from shop.cart import add_item
import shop.payments as pay

Where Python looks for modules

sys.path lists the folders searched in order: the script's folder, then the standard library, then installed packages.

python
import sys
print(sys.path[:3])

Exploring a module

python
import math
print([name for name in dir(math) if not name.startswith("_")][:10])
help(math.gcd)

Useful standard library modules

ModulePurpose
os, pathlib, shutilFiles and folders
sysInterpreter details, command line arguments
datetime, timeDates and timing
math, statistics, randomMaths
json, csvData formats
reRegular expressions
collections, itertools, functoolsData structure and function helpers
loggingStructured log output
unittestTesting
urllib, httpNetworking

Practice

  1. Create geometry.py with circle_area(r) and rect_area(w, h), then import and use both from another file.
  2. Add a __main__ guard to geometry.py that prints a demo when run directly, and check it does not print when imported.
  3. Use dir() on the random module and try three functions you have not used before.