콘텐츠로 이동

Modules and Packages

Ⅴ Modules, Packages

01. What is a Module?

A module is a .py file containing Python code. It groups related functions, variables, and classes for reuse.

my_project/
├── main.py       ← file that uses the module
└── math_utils.py ← module (file with grouped functions)

3 Ways to Import

# Method 1: import the entire module
import math
print(math.sqrt(16))    # 4.0

# Method 2: import specific names
from math import sqrt, pi
print(sqrt(16))         # 4.0  (no math. prefix needed)

# Method 3: import with an alias
import math as m
print(m.sqrt(16))       # 4.0

02. Creating a Module

Any .py file you create is a module.

# calc.py
PI = 3.14159

def add(a, b):
    return a + b

def circle_area(r):
    return PI * r * r
# main.py
import calc
print(calc.add(3, 5))        # 8
print(calc.circle_area(2))   # 12.56636

if __name__ == "__main__": Pattern

# calc.py
def add(a, b):
    return a + b

if __name__ == "__main__":
    # runs ONLY when this file is run directly
    # does NOT run when imported
    print(add(1, 2))
How it runs __name__ if block?
python calc.py "__main__" Runs
import calc "calc" Does NOT run

03. What is a Package?

A package is a folder of modules with an __init__.py file.

my_project/
├── main.py
└── utils/
    ├── __init__.py    ← marks this folder as a package
    ├── string_utils.py
    └── math_utils.py
from utils.math_utils import add
print(add(3, 4))

04. Useful Standard Library Modules

math

import math
print(math.sqrt(25))     # 5.0
print(math.pi)           # 3.141592...
print(math.floor(3.9))   # 3
print(math.ceil(3.1))    # 4
print(math.factorial(5)) # 120

random

import random
print(random.random())          # float in [0.0, 1.0)
print(random.randint(1, 6))     # integer 1–6
print(random.choice(["a","b"])) # random element from list
random.shuffle([1,2,3,4,5])     # shuffle a list in place

datetime

from datetime import datetime, date
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))   # 2026-05-23 10:30
today = date.today()
print(today)                            # 2026-05-23

os

import os
print(os.getcwd())                    # current directory
print(os.path.exists("test.txt"))     # True/False
print(os.path.join("data", "f.txt"))  # "data/f.txt"

json

import json
data = {"name": "Alice", "scores": [90, 85]}
json_str = json.dumps(data, indent=2)   # dict → JSON string
parsed  = json.loads(json_str)          # JSON string → dict

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)        # write to file
with open("data.json", "r") as f:
    loaded = json.load(f)               # read from file

Key Summary

Concept Description
Module A .py file grouping related code
import module Import the whole module
from module import name Import a specific name
import module as alias Import with a short alias
__name__ == "__main__" Code that runs only when executed directly
Package A folder of modules with __init__.py
math Math functions (sqrt, pi, floor, ceil)
random Random numbers (random, randint, choice, shuffle)
datetime Date and time handling
json JSON encode/decode and file I/O