Skip to content

Modules and Packages

Creating and Importing Modules

Python Modules

Creating a Module

python
# math_utils.py - Math utilities module
"""Math utilities module, providing basic math operations"""

PI = 3.14159

def add(a, b):
    """Returns the sum of two numbers"""
    return a + b

def subtract(a, b):
    """Returns the difference of two numbers"""
    return a - b

def multiply(a, b):
    """Returns the product of two numbers"""
    return a * b

def divide(a, b):
    """Returns the quotient of two numbers"""
    if b == 0:
        raise ValueError("Divisor cannot be zero")
    return a / b

def power(base, exponent):
    """Returns base to the power of exponent"""
    return base ** exponent

# Module-level code
if __name__ == "__main__":
    # Test code
    print("Testing math utilities module:")
    print(f"PI = {PI}")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"10 - 4 = {subtract(10, 4)}")
    print(f"6 * 7 = {multiply(6, 7)}")
    print(f"15 / 3 = {divide(15, 3)}")
    print(f"2^8 = {power(2, 8)}")

Importing a Module

python
# main.py - Main program file
# Method 1: Import the entire module
import math_utils

result = math_utils.add(5, 3)
print(result)  # 8

# Method 2: Import specific functions
from math_utils import add, multiply

result = add(10, 5)
print(result)  # 15

# Method 3: Import all functions (not recommended)
from math_utils import *

result = subtract(20, 8)
print(result)  # 12

# Method 4: Use an alias
import math_utils as mu

result = mu.power(2, 10)
print(result)  # 1024

# Method 5: Alias a function
from math_utils import add as addition

result = addition(7, 9)
print(result)  # 16

JavaScript Modules

Creating a Module

javascript
// mathUtils.js - Math utilities module
/**
 * Math utilities module, providing basic math operations
 */

export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    throw new Error("Divisor cannot be zero");
  }
  return a / b;
}

export function power(base, exponent) {
  return base ** exponent;
}

// Default export
export default {
  add,
  subtract,
  multiply,
  divide,
  power,
  PI,
};

Importing a Module

javascript
// main.js - Main program file
// Method 1: Import the entire module
import * as mathUtils from "./mathUtils.js";

const result = mathUtils.add(5, 3);
console.log(result); // 8

// Method 2: Import specific functions
import { add, multiply } from "./mathUtils.js";

const result2 = add(10, 5);
console.log(result2); // 15

// Method 3: Import the default export
import mathUtilsDefault from "./mathUtils.js";

const result3 = mathUtilsDefault.add(7, 9);
console.log(result3); // 16

// Method 4: Use an alias
import * as mu from "./mathUtils.js";

const result4 = mu.power(2, 10);
console.log(result4); // 1024

// Method 5: Alias a function
import { add as addition } from "./mathUtils.js";

const result5 = addition(7, 9);
console.log(result5); // 16

Module Comparison

FeaturePythonJavaScript
File Extension.py.js
Import Syntaximport moduleimport { func } from './module.js'
Default Export__all__export default
Namespacemodule.function()module.function()
Aliasimport module as aliasimport * as alias

Creating and Importing Packages

Python Packages

Creating a Package Structure

my_package/
├── __init__.py
├── math_utils.py
├── string_utils.py
└── data_utils.py

Package Initialization File

python
# my_package/__init__.py
"""My utilities package"""

from .math_utils import add, subtract, multiply, divide
from .string_utils import reverse_string, count_words
from .data_utils import load_data, save_data

__version__ = "1.0.0"
__author__ = "Your Name"

# Define the public API of the package
__all__ = [
    'add', 'subtract', 'multiply', 'divide',
    'reverse_string', 'count_words',
    'load_data', 'save_data'
]

# Package-level configuration
PACKAGE_NAME = "MyPackage"

Modules in the Package

python
# my_package/math_utils.py
"""Math utilities module"""

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

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

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Divisor cannot be zero")
    return a / b
python
# my_package/string_utils.py
"""String utilities module"""

def reverse_string(text):
    """Reverses a string"""
    return text[::-1]

def count_words(text):
    """Counts the number of words"""
    return len(text.split())
python
# my_package/data_utils.py
"""Data processing utilities module"""

import json

def load_data(filename):
    """Loads data from a JSON file"""
    with open(filename, 'r', encoding='utf-8') as f:
        return json.load(f)

def save_data(data, filename):
    """Saves data to a JSON file"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

Importing from a Package

python
# main.py
# Import the entire package
import my_package

result = my_package.add(10, 20)
print(result)  # 30

# Import a specific module from the package
from my_package import string_utils

reversed_text = string_utils.reverse_string("hello")
print(reversed_text)  # olleh

# Import a specific function from the package
from my_package import multiply

result = multiply(5, 5)
print(result)  # 25

JavaScript Packages

Creating a Package Structure

my-package/
├── index.js
├── mathUtils.js
├── stringUtils.js
└── dataUtils.js

Package Entry File

javascript
// my-package/index.js
/**
 * My utilities package
 */

import { add, subtract, multiply, divide } from "./mathUtils.js";
import { reverseString, countWords } from "./stringUtils.js";
import { loadData, saveData } from "./dataUtils.js";

export const version = "1.0.0";
export const author = "Your Name";

export {
  add,
  subtract,
  multiply,
  divide,
  reverseString,
  countWords,
  loadData,
  saveData,
};

Modules in the Package

javascript
// my-package/mathUtils.js
export function add(a, b) {
  return a + b;
}
export function subtract(a, b) {
  return a - b;
}
// ...
javascript
// my-package/stringUtils.js
export function reverseString(text) {
  return text.split("").reverse().join("");
}
export function countWords(text) {
  return text.split(/\s+/).length;
}

Importing from a Package

javascript
// main.js
// Import specific functions
import { add, reverseString } from "./my-package/index.js";

console.log(add(10, 20)); // 30
console.log(reverseString("hello")); // olleh

// Import the entire package as a namespace
import * as myPackage from "./my-package/index.js";

console.log(myPackage.multiply(5, 5)); // 25

Built-in Modules

Python Built-in Modules

python
# Python - Using built-in modules
import os
import sys
import datetime
import math
import random

print(f"OS: {os.name}")
print(f"Python version: {sys.version}")
print(f"Current time: {datetime.datetime.now()}")
print(f"Pi: {math.pi}")
print(f"Random number: {random.randint(1, 100)}")

JavaScript Built-in Modules

javascript
// JavaScript - Using built-in modules (Node.js)
import os from "os";
import path from "path";
import fs from "fs";

console.log(`OS platform: ${os.platform()}`);
console.log(`Current file path: ${path.resolve()}`);
fs.readdir(".", (err, files) => {
  if (err) throw err;
  console.log(`Files in current directory: ${files}`);
});

Summary

  • Python: import statement, packages are directories with __init__.py.
  • JavaScript: import/export syntax, packages managed via package.json.

Exercises

  1. Create a Python module with a utility function and import it.
  2. Create a JavaScript module and import it.
  3. Structure a simple package in Python.

Next Steps

Now you know about modules and packages. Next, we'll learn about file operations.