Chapters
Python114 chapters

Modules and the standard libraryChapter 70 of 114

Modules

Split code across files, and pull in what the standard library already has.

Importing

A module is a .py file. import runs it once and gives you its contents:

Python
import math

print(math.pi)
print(math.sqrt(16))

Output

3.141592653589793
4.0

The name stays attached, which is a feature: math.sqrt says where sqrt came from.

from ... import

Pull specific names straight into your file:

Python
from math import pi, sqrt

print(pi)
print(sqrt(16))

Output

3.141592653589793
4.0

Shorter to use, and you lose the origin. Fine for a handful of well-known names, worse when two modules both have a parse.

Renaming on import

Python
import math as m
from math import sqrt as square_root

print(m.pi)
print(square_root(9))

Output

3.141592653589793
3.0

Use it for genuinely long names or the conventional short forms — import numpy as np — rather than to save three characters.

Your own modules

If helpers.py sits next to your script:

Python
# helpers.py
def shout(word):
    return word.upper()
Python
# main.py
import helpers
print(helpers.shout("hey"))

Python looks for modules in the current directory first, then the standard library, then installed packages. That order is why naming your file math.py breaks every import of the real math in that folder.

Modules run once

The whole file executes on the first import. Later imports reuse the result:

Python
import math
import math

print("imported twice, executed once")

Output

imported twice, executed once

Anything at the top level of a module runs at import time. Keep that to definitions and constants — a print or a network call there fires whenever anyone imports you.

The __name__ == "__main__" guard

__name__ is "__main__" when a file is run directly, and the module's name when it is imported. The guard lets a file be both:

Python
def shout(word):
    return word.upper()

if __name__ == "__main__":
    print(shout("run directly"))

Import it and you get shout with nothing printed. Run it and the demo happens.

What is in a module

Python
import math

print(len(dir(math)) > 30)
print("sqrt" in dir(math))
print(math.__name__)

Output

True
True
math

help(math) at the prompt prints the documentation, which is often faster than searching the web.

Packages

A folder of modules with an __init__.py is a package, and you import through the dots:

Python
from collections import Counter
from os import path

print(Counter("aab").most_common(1))
print(path.splitext("report.pdf"))

Output

[('a', 2)]
('report', '.pdf')

The standard library is large

Before installing anything, check whether Python already has it: math, random, datetime, json, re, pathlib, collections, itertools, csv, sqlite3, urllib, unittest, statistics.

Python
import random
random.seed(42)
print(random.randint(1, 100))
print(random.choice(["a", "b", "c"]))

Output

82
a

seed() makes the sequence repeatable, which is how a test can check code that uses randomness.

Test yourself

2 questions

Why is naming your file math.py a problem?

Show the answer

Python searches the current directory first, so it shadows the real math module — The same applies to random.py, json.py and every other stdlib name.

What is the __name__ == "__main__" guard for?

Show the answer

Running code only when the file is executed directly, not when imported — It lets one file be both an importable module and a runnable script.

Next chapter

PIP

Install packages other people wrote, and pin what your project needs.