Skip to content

Latest commit

Β 

History

History
123 lines (92 loc) Β· 2.57 KB

File metadata and controls

123 lines (92 loc) Β· 2.57 KB

🐍 15 – Modules & Packages

🎯 What You'll Learn

  • Import modules and packages
  • Create your own modules
  • __name__ == "__main__" pattern
  • Relative imports

πŸ“Œ JS vs Python β€” Side by Side

Concept JavaScript Python
Import all import fs from 'fs' import os
Named import import { readFile } from os import getcwd
Alias import _ as lodash import numpy as np
Re-export export { fn } just define in module
Module entry no equivalent if __name__ == "__main__":

πŸ’‘ Importing

# Import whole module
import math
print(math.sqrt(16))    # 4.0

# Import specific items
from math import sqrt, pi, floor
print(sqrt(16))         # 4.0 β€” no math. prefix needed

# Import with alias
import numpy as np          # common convention
import pandas as pd

# Import everything (avoid in production)
from math import *
print(sqrt(16))         # works, but pollutes namespace

πŸ’‘ Creating Your Own Module

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

def subtract(a, b):
    return a - b

PI = 3.14159

# The __name__ guard β€” runs only when executed directly
if __name__ == "__main__":
    print("Testing math_utils directly")
    print(add(2, 3))     # 5
# main.py β€” import from math_utils
from math_utils import add, PI
import math_utils

print(add(10, 5))         # 15
print(PI)                 # 3.14159
print(math_utils.subtract(10, 3))  # 7

πŸ’‘ Package Structure

A package is a directory with an __init__.py file.

my_project/
β”œβ”€β”€ main.py
└── utils/
    β”œβ”€β”€ __init__.py        ← makes utils/ a package
    β”œβ”€β”€ math_utils.py
    └── string_utils.py
# main.py
from utils.math_utils import add
from utils import string_utils

print(add(1, 2))

πŸ’‘ Standard Library Highlights

No install needed β€” built into Python:

import os           # file system, env vars
import sys          # system info, argv
import json         # JSON encode/decode
import csv          # CSV files
import re           # regular expressions
import math         # math functions
import random       # random numbers
import datetime     # date and time
import pathlib      # modern file paths
import collections  # Counter, defaultdict, deque
import itertools    # powerful iteration tools
import functools    # lru_cache, partial, reduce
import time         # sleep, timing
import hashlib      # MD5, SHA hashing

πŸ”— Next Lesson

πŸ‘‰ 16 – pip & Virtual Environments