TExcelTAD
Home › Python › Python Modules

Python Modules

A module is simply a .py file containing Python code — functions, classes and variables — that other code can import and reuse. Modules keep big programs organised, and they're how you tap into Python's enormous standard library.

Importing a module

python · try it yourself
import math

print(math.sqrt(81))
print(math.pi)
print(math.floor(7.8))
9.0
3.141592653589793
7

After import math, everything in the module is reached through the math. prefix. This namespace keeps names from colliding: your own floor variable won't clash with math.floor.

Import styles

Form Use it as Notes
import math math.sqrt(2) clearest; recommended default
import statistics as st st.mean(data) alias for long names
from math import sqrt, pi sqrt(2) import specific names
from math import * sqrt(2) imports everything — avoid, it hides where names come from
python · try it yourself
import statistics as st
from math import sqrt, pi
from collections import Counter

scores = [72, 85, 90, 85, 64]
print(st.mean(scores), st.median(scores))
print(round(sqrt(2), 4), round(pi, 2))
print(Counter("mississippi").most_common(2))
79.2 85
1.4142 3.14
[('i', 4), ('s', 4)]

Creating your own module

Save some code in a file, for example greetings.py:

python
# greetings.py
DEFAULT_NAME = "friend"

def hello(name=DEFAULT_NAME):
    return f"Hello, {name}!"

def goodbye(name=DEFAULT_NAME):
    return f"Goodbye, {name}."

Any other file in the same folder can now import it, using the file name without .py:

python
# main.py
import greetings
from greetings import goodbye

print(greetings.hello("Vinh"))
print(goodbye())
bash · try it yourself
python3 main.py
Hello, Vinh!
Goodbye, friend.

Note: Each playground on this site is a single file, so the multi-file example above is shown rather than run. Try it on your own computer.

if __name__ == "__main__":

When Python runs a file directly, it sets that module's __name__ to "__main__". When the file is imported, __name__ is the module's name instead. This lets a file act both as a reusable module and as a script:

python
# geometry.py
def area(r):
    return 3.14159 * r * r

if __name__ == "__main__":
    # runs only when this file is executed, not when imported
    print("Self-test:", round(area(2), 2))

Running the file directly executes the self-test; importing it from another file does not:

bash · try it yourself
python3 geometry.py
python3 -c "import geometry; print(geometry.area(1))"
Self-test: 12.57
3.14159

Exploring a module

dir() lists the names a module defines, and help() prints its documentation. Many modules also have a version or a docstring:

python · try it yourself
import string

public = [name for name in dir(string) if not name.startswith("_")]
print(public[:6])
print(string.ascii_lowercase)
print(string.digits)
['Formatter', 'Template', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords']
abcdefghijklmnopqrstuvwxyz
0123456789

Packages

A package is a folder of modules. It's how larger libraries are organised, and you import from it with dotted names:

text
shop/
    __init__.py
    cart.py
    payments/
        __init__.py
        card.py
python
from shop.cart import Cart
from shop.payments import card

The standard library uses packages too — os.path, json.decoder, urllib.request.

python · try it yourself
import os.path
from urllib.parse import urlparse

print(os.path.splitext("report.final.pdf"))
url = urlparse("https://example.com:8080/docs/page?lang=en")
print(url.hostname, url.port, url.path, url.query)
('report.final', '.pdf')
example.com 8080 /docs/page lang=en

Where does Python look for modules?

When you import name, Python searches, in order: the folder of the script being run, the folders in the PYTHONPATH environment variable, and the standard library and installed packages (site-packages). The full list lives in sys.path.

Tip: Never name your own file after a module you want to use — a random.py or json.py in your project folder will be imported instead of the real one!

A tour of useful standard modules

Module For
math, statistics maths and basic stats
datetime dates and times
json, csv data formats
re regular expressions
os, pathlib, shutil files and folders
collections, itertools, functools extra data structures and tools
random random numbers
urllib, http web requests and servers

Test yourself

After from math import sqrt, how do you call the square-root function?

  1. math.sqrt(9)
  2. sqrt(9)
  3. math::sqrt(9)
  4. import.sqrt(9)

What is __name__ when a file is run directly as a script?

  1. The file name
  2. "__main__"
  3. "script"
  4. None

What is a package?

  1. A single .py file
  2. A compiled module
  3. A folder of modules that can be imported with dotted names
  4. A pip command