Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 1 of 8

A module is a file of Python code you can use from another file. Python ships with hundreds of them — the standard library — covering maths, dates, randomness, files, and much more.

You've already used two: csv and json in Module 6.

import module

import math

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

import math makes the module available under the name math. Everything inside is reached with a dot — math.sqrt, math.pi.

That prefix isn't clutter, it's information: math.sqrt(16) tells the reader exactly where sqrt came from.

from module import name

Import specific things directly into your file:

from math import sqrt, pi

print(sqrt(16))
print(pi)

Now you call sqrt() with no prefix. Shorter, but you lose the origin, and you risk a clash — if you later define your own sqrt, one silently overwrites the other.

Use import module by default. Use from ... import when you'll reference a name many times and its origin is obvious.

import module as alias

Rename on import, usually to shorten a long name:

import datetime as dt

print(dt.date(2026, 1, 15))

Some aliases are near-universal conventions in the wider ecosystem — import pandas as pd, import numpy as np. Stick to the conventional alias where one exists.

You can alias individual names too:

from math import sqrt as square_root

print(square_root(25))

Never use import *

from math import *

This dumps every name from the module into your file. It looks convenient and causes real problems: you can't tell where anything came from, and it silently overwrites names that clash. math.pow and the built-in pow behave differently, for instance. Avoid it.

Importing several

import math
import json
import random

print(math.floor(3.7))
print(json.dumps({"a": 1}))
print(random.choice(["only"]))

One import per line, at the top of the file. PEP 8 orders them in three groups, separated by blank lines:

  1. standard library
  2. third-party packages
  3. your own modules

Where do modules come from?

import math makes Python search a list of directories, in order: the current directory first, then the standard library, then installed packages.

import sys

print(type(sys.path))
print(len(sys.path) > 0)

That "current directory first" rule matters: naming your own file math.py shadows the real module and breaks anything that imports it. Don't name files after standard library modules.

Try it yourself

Try all three import styles.

Checkpoint

  • A module is a file of Python code; the standard library ships hundreds.
  • import m then m.thing; from m import thing then thing; import m as alias to rename.
  • Never from m import * — it hides origins and causes silent clashes.
  • Imports go at the top: standard library, third-party, then local.
  • Don't name your files after standard library modules.

Questions about this lesson

Log in to ask a question.