Modules & Packages
import, stdlib highlights, __name__, and packaging basics
Skills taught: python.modules, python.import, python.stdlib
Importing modules
# Import the whole module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# Import specific names
from math import sqrt, ceil, floor
print(sqrt(25)) # 5.0
# Import with alias
import datetime as dt
print(dt.datetime.now())
from datetime import datetime, timedelta
tomorrow = datetime.now() + timedelta(days=1)
print(tomorrow)
# Import your own module
# --- utils.py ---
# def greet(name):
# return f'Hello, {name}!'
# --- main.py ---
# import utils
# print(utils.greet('Prashant'))
# --- or ---
# from utils import greet
# print(greet('Prashant'))
Key stdlib modules
import os, sys, json, random, re
from pathlib import Path
from datetime import datetime
from collections import Counter, defaultdict
# os — operating system interface
print(os.getcwd()) # current directory
print(os.listdir('.')) # files in current dir
print(os.environ.get('PATH', 'not set'))
# sys — Python interpreter
print(sys.version) # Python 3.12.x
print(sys.argv) # command-line arguments
print(sys.platform) # 'win32', 'linux', 'darwin'
# json — JSON encoding/decoding
data = {'name': 'Prashant', 'score': 95}
json_str = json.dumps(data, indent=2) # dict → string
back = json.loads(json_str) # string → dict
# random — random numbers
print(random.randint(1, 10)) # random int 1-10
print(random.choice(['a','b','c'])) # random element
items = [1, 2, 3, 4, 5]
random.shuffle(items) # shuffle in place
print(random.sample(items, k=3)) # 3 random items
# re — regular expressions
import re
pattern = r'\b\d{4}\b' # 4-digit numbers
text = 'Year 2024 and 2025 were big'
matches = re.findall(pattern, text) # ['2024', '2025']
# collections — powerful container types
words = ['apple','banana','apple','cherry','banana','apple']
print(Counter(words)) # Counter({'apple': 3, ...})
dd = defaultdict(list)
dd['fruits'].append('apple') # no KeyError!
The __name__ guard
# utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# This block ONLY runs when this file is executed directly
# It does NOT run when the file is imported by another module
if __name__ == '__main__':
print('Testing utils.py...')
print(add(2, 3)) # 5
print(multiply(3, 4)) # 12
print('All tests passed!')
# When you run: python utils.py → __name__ == '__main__'
# When you do: import utils → __name__ == 'utils'
# The if block is skipped on import — test code doesn't leak!
Frequently Asked Questions
What is the difference between a module and a package?
A module is a single .py file. A package is a directory containing multiple modules and an __init__.py file (which can be empty). Packages let you organise large projects: import mypackage.utils.helpers accesses helpers.py inside mypackage/utils/.
How do I find what's inside a module?
In the REPL: import math; dir(math) lists all names. help(math.sqrt) shows the docstring. help(math) shows the full module docs. In code: hasattr(module, 'attr') and getattr(module, 'attr') for programmatic access.