Python Basics — Importing Modules

3 minute read

Importing Modules

A module is simply a .py file containing Python code. Importing lets you use code defined in other modules — whether built-in, third-party, or your own.

import Statement

import math

print(math.pi)           # 3.141592653589793
print(math.sqrt(16))     # 4.0
print(math.ceil(4.3))    # 5

With import, you access module contents using dot notation: module.name.

from…import

Import specific names directly into your namespace:

from math import sqrt, pi

print(sqrt(16))   # 4.0
print(pi)          # 3.141592653589793
# print(math.ceil(4.3))  # NameError — math not imported, only sqrt and pi

import…as (Aliasing)

Give a module or function a shorter name:

import datetime as dt

now = dt.datetime.now()
print(now.strftime("%Y-%m-%d"))  # 2025-03-03

from collections import OrderedDict as OD

order = OD(a=1, b=2, c=3)
print(order)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

Common aliases you’ll see in the wild:

Module Common Alias
numpy np
pandas pd
matplotlib.pyplot plt
datetime dt
tensorflow tf

Import Order — PEP 8

PEP 8 recommends organizing imports in this order, separated by blank lines:

# 1. Standard library imports
import os
import sys
from datetime import datetime

# 2. Third-party imports
import requests
import numpy as np

# 3. Local application imports
from mypackage import helpers
from mypackage.utils import validate

__name__ and if __name__ == "__main__":

Every module has a special __name__ attribute:

  • When run directly: __name__ is "__main__"
  • When imported: __name__ is the module’s filename (without .py)
# greetings.py
def hello(name):
    return f"Hello, {name}!"

print(f"__name__ = {__name__}")

if __name__ == "__main__":
    # This block only runs when the file is executed directly
    print(hello("World"))
# Run directly
python greetings.py
# Output:
# __name__ = __main__
# Hello, World!
# In another file
import greetings
# Output: __name__ = greetings
# (The hello("World") call is NOT executed)

print(greetings.hello("Alice"))  # Hello, Alice!

Why this matters: It lets a file work both as an importable module AND as a standalone script.

Module Search Path

When you write import mymodule, Python looks in this order:

  1. Current directory (or the script’s directory)
  2. PYTHONPATH environment variable directories
  3. Installation-dependent default directories (standard library, site-packages)

You can inspect the search path:

import sys
for path in sys.path:
    print(path)
# /Users/you/project     ← current directory
# /usr/lib/python3.12    ← standard library
# /usr/lib/python3.12/lib-dynload
# /usr/lib/python3/dist-packages  ← third-party packages

Importing Everything — from module import *

from math import *   # imports ALL public names from math

print(sqrt(25))  # 5.0
print(pi)        # 3.14...

Avoid import * in production code — it pollutes your namespace and makes it unclear where names come from. Use it only in interactive sessions or notebooks.

Checking What’s in a Module

import math

# List all names in the module
print(dir(math))
# ['__doc__', '__name__', ..., 'ceil', 'cos', 'e', 'floor', 'log', 'pi', 'sqrt', ...]

# Read the module's docstring
print(math.__doc__[:100])

# Get help on a specific function
help(math.sqrt)

Common Import Mistakes

# ❌ Circular import — module A imports B, B imports A
# Fix: restructure code or use late imports

# ❌ Importing inside a loop — slow
for i in range(1000):
    import math  # don't do this — import once at the top

# ❌ Shadowing module names
# Don't name your file math.py, random.py, etc.
# It will shadow the built-in module!

# ❌ Forgetting that import executes the module
# All top-level code in a module runs on import

Summary

Style Example When to Use
import module import math Most common — keeps namespace clean
from module import name from math import sqrt When you use specific names frequently
import module as alias import numpy as np Long module names or common conventions
from module import * from math import * Only in interactive sessions
  • Follow PEP 8 import order: stdlib → third-party → local
  • Use if __name__ == "__main__": to guard script code
  • Never name your files after stdlib modules
  • Use dir(module) to explore module contents

Next up: Standard Library Tour →

Updated: