Part 07 / Topic 2 of 9
Import styles
There are three common ways to import. Pick the one that keeps your code clear.
Real-world example: a dice game and a date stamp.
import math # 1. whole module -> use math.floor
from random import randint # 2. one name -> use randint directly
import datetime as dt # 3. alias -> use dt.date
print(math.floor(7.9)) # 7
print(1 <= randint(1, 6) <= 6) # True
print(dt.date(2025, 8, 15)) # 2025-08-15
| Style | You write | Good for |
|---|---|---|
import math |
math.sqrt(9) |
Most cases, clear where names come from |
from math import sqrt |
sqrt(9) |
A few names you use a lot |
import datetime as dt |
dt.date.today() |
Long module names |
from math import * |
sqrt(9) |
โ Avoid: hides where names came from, can overwrite your names |
๐ Going deeper:
from shop_utils import GST_RATEdoes not copy anything. It binds a new nameGST_RATEin your file to the same object thatshop_utils.GST_RATEpoints to right now (GST_RATE is shop_utils.GST_RATEisTrue). But the two names are separate labels: if code later doesshop_utils.GST_RATE = 0.12, only the module's label moves to the new value, and yourGST_RATEstill says0.18. When a value may change, useimport shop_utilsand readshop_utils.GST_RATE.
Done here? The practice set for Part 7 โ 7 exercises with solutions โ is on the part page.