SyntaxStudy
Sign Up
Python Beginner 7 min read

Importing Modules

Importing Modules

Python's import system lets you bring in code from the standard library, third-party packages, or your own files.

Basic import

import math
print(math.sqrt(16))    # 4.0
print(math.pi)          # 3.14159...

from ... import

from math import sqrt, pi, ceil
print(sqrt(25))   # 5.0
print(ceil(4.2))  # 5
# No "math." prefix needed

import ... as (Alias)

import numpy as np           # common alias
import pandas as pd          # common alias
import matplotlib.pyplot as plt

from datetime import datetime as dt
print(dt.now())

Wildcard Import (Avoid)

from math import *    # imports everything — pollutes namespace
print(sin(0))         # works but hard to trace where it came from

Conditional Import

try:
    import ujson as json   # fast JSON library
except ImportError:
    import json            # fallback to stdlib

Reload a Module

import importlib
import mymodule
importlib.reload(mymodule)   # force re-read from disk
Example
import math
import random
from datetime import date, timedelta

print(f"sqrt(144) = {math.sqrt(144)}")
print(f"Random 1-100: {random.randint(1, 100)}")
print(f"Today: {date.today()}")
print(f"Next week: {date.today() + timedelta(weeks=1)}")
Pro Tip

Use explicit imports (from module import name) over wildcard imports — they make it clear where each name comes from and prevent accidental shadowing.