Cyber Services / All lessons / Python Programming / Creating and Importing Modules

Creating and Importing Modules

Module 17 of 31 · 3 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Modular Programming

What Is a Module?

A module in Python is simply a .py file containing Python code—functions, classes, variables, or runnable statements. Modules enable **code reuse**, **organization**, and **separation of concerns**.

  • Each Python file is automatically a module.
  • Modules can be imported into other scripts.
  • Standard library (e.g., math, os) and third-party packages are built from modules.
  • Modular code is easier to test, debug, and maintain.

Creating Your First Module

Let’s create a module called math_utils.py:

1. math_utils.py – A Custom Module
# math_utils.py

def add(a, b):
    """Return sum of two numbers."""
    return a + b

def multiply(a, b):
    """Return product of two numbers."""
    return a * b

PI = 3.14159

# This runs only if the file is executed directly
if __name__ == "__main__":
    print("Testing module:")
    print("2 + 3 =", add(2, 3))
    print("2 * 3 =", multiply(2, 3))

Importing Modules

Now use this module in another file, e.g., main.py.

2. Basic Import
# main.py
import math_utils

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

print(math_utils.PI)  # 3.14159
3. Import with Alias
import math_utils as mu

print(mu.multiply(4, 7))  # 28
4. Import Specific Items
from math_utils import add, PI

print(add(1, 2))  # 3
print(PI)         # 3.14159
5. Import All (Use Sparingly!)
from math_utils import *

print(multiply(3, 3))  # 9
# ⚠️ Avoid in large projects—pollutes namespace!

The __name__ == "__main__" Guard

This idiom ensures code runs **only when the file is executed directly**, not when imported.

  • When you run python math_utils.py → __name__ is "__main__".
  • When you import math_utils → __name__ is "math_utils".

Use it for **module testing** or **demo code**.

6. Safe Module Execution
# In any module
def main():
    print("Running as script!")

if __name__ == "__main__":
    main()  # Only runs if file is executed directly

Python’s Module Search Path

When you import xyz, Python looks for xyz.py in:

  1. The current directory
  2. Directories in PYTHONPATH environment variable
  3. Standard library locations
  4. Site-packages (for installed packages)

You can view the search path with:

import sys
print(sys.path)
7. Adding Custom Paths (Advanced)
import sys
sys.path.append("/path/to/your/modules")

# Now you can import from that directory
import my_custom_module

Standard Library Modules (Examples)

8. Using math
import math
print(math.sqrt(16))    # 4.0
print(math.pi)          # 3.14159...
9. Using random
from random import randint
print(randint(1, 10))  # Random int between 1–10
10. Using os for File Paths
import os
current = os.getcwd()
print("Current directory:", current)

Creating Packages (Multiple Modules)

A package is a directory containing multiple modules and an __init__.py file (can be empty).

my_package/
├── __init__.py
├── math_ops.py
└── string_ops.py
11. Import from Package
# Import entire module
from my_package import math_ops

# Import specific function
from my_package.string_ops import reverse_string

# Relative import (inside package)
# from .math_ops import add
12. __init__.py Controls Public API
# my_package/__init__.py
from .math_ops import add, multiply
from .string_ops import reverse_string

# Now users can do:
# from my_package import add, reverse_string

Best Practices

  • ✅ **Use descriptive module names** (e.g., data_validator.py, not utils.py).
  • ✅ **Avoid from module import ***—it hides dependencies and causes naming conflicts.
  • ✅ **Always use if __name__ == "__main__":** for test/demo code.
  • ✅ **Group related functions** into logical modules.
  • ✅ **Document your modules** with docstrings and comments.
  • ✅ **Keep modules focused**—one responsibility per module.

Common Pitfalls

  • ❌ Naming your module the same as a standard library module (e.g., json.py).
  • ❌ Circular imports (Module A imports B, and B imports A).
  • ❌ Forgetting __init__.py in packages (required in Python < 3.3).
  • ❌ Modifying sys.path unnecessarily—use virtual environments instead.

Key Takeaways

  • Every .py file is a **module**.
  • Use import, from ... import, or aliases to reuse code.
  • The __name__ == "__main__" guard enables **dual-use**: importable + executable.
  • Modular programming = **cleaner, scalable, and professional** code.
  • Packages organize **multiple related modules** into a single namespace.
Modules (31) ← Python Programming