Tutorials Logic, IN info@tutorialslogic.com

Modules in Python import, packages, __init__

Python Modules

A module is a Python file that can hold functions, classes, constants, and runnable code.

Imports let one file reuse names from another file, which keeps programs organized as they grow.

Good module design keeps side effects small, gives files clear names, and avoids circular imports.

Python Module

A module is a Python file (.py) containing functions, classes, and variables that you can reuse in other files. Python has a huge standard library of built-in modules, plus thousands of third-party packages.

Import Modules

Import Syntax

Import Syntax
import math                    # import entire module
import math as m               # import with alias
from math import sqrt, pi      # import specific names
from math import *             # import everything (avoid this)

# Using the module
print(math.sqrt(16))   # 4.0
print(m.pi)            # 3.141592653589793
print(sqrt(25))        # 5.0
print(pi)              # 3.141592653589793

# Common standard library modules
import os
import sys
import json
import datetime
import random
import re
import collections
import itertools
import functools

Create a Module

Custom Module

Custom Module
# mathutils.py
PI = 3.14159

def circle_area(radius: float) -> float:
    """Return the area of a circle."""
    return PI * radius ** 2

def circle_perimeter(radius: float) -> float:
    """Return the perimeter of a circle."""
    return 2 * PI * radius

def is_prime(number: int) -> bool:
    """Return whether number is prime."""
    if number < 2:
        return False
    for divisor in range(2, int(number ** 0.5) + 1):
        if number % divisor == 0:
            return False
    return True

Import a Function from Your File

Import a Function from Your File
# main.py - in the same directory
import mathutils
from mathutils import is_prime

print(mathutils.circle_area(5))       # 78.53975
print(mathutils.circle_perimeter(5))  # 31.4159
print(is_prime(17))                   # True
print(is_prime(20))                   # False

__name__ Variable

Every module has a __name__ variable. When run directly, it equals "__main__". When imported, it equals the module's filename.

__name__ Guard

__name__ Guard
def greet(name):
    return f"Hello, {name}!"

def main():
    print(greet("World"))

# This block only runs when the file is executed directly
# NOT when it's imported by another module
if __name__ == "__main__":
    main()

Packages

A package is a directory containing multiple modules and an __init__.py file.

Package Structure

Package Structure
mypackage/
|-- __init__.py       # makes it a package
|-- math_utils.py
|-- string_utils.py
`-- io/
    |-- __init__.py
    `-- file_reader.py

# Importing from a package
from mypackage import math_utils
from mypackage.string_utils import capitalize
from mypackage.io.file_reader import read_csv

Standard Library Modules

Standard Library Examples

Standard Library Examples
import os
import random
import json
from collections import Counter, defaultdict

# os - file system operations
print(os.getcwd())                    # current directory
print(os.path.join("folder", "file")) # folder/file
os.makedirs("new_dir", exist_ok=True)

# random - random numbers
print(random.randint(1, 10))          # random int 1-10
print(random.choice(["a", "b", "c"])) # random item
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)

# json - encode/decode JSON
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, indent=2)
print(json_str)
parsed = json.loads(json_str)
print(parsed["name"])   # Alice

# collections.Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count)                    # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(count.most_common(2))     # [('apple', 3), ('banana', 2)]

# collections.defaultdict
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd)  # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
Module readiness check

Can You Split Code Into Modules?

4 checks
  • A module is a Python file (.py) containing functions, classes, and variables that you can reuse in other files.
  • Python has a huge standard library of built-in modules, plus thousands of third-party packages.
  • When imported, it equals the module's filename.
  • A regular package groups modules in a directory whose __init__.py can define its public package surface.

Module Decisions

0 of 2 checked

Q1. Why should you avoid naming your file json.py?

Q2. What does if __name__ == "__main__" protect?

Import Problems to Catch

  • Naming a file like a library

    Avoid names such as random.py, json.py, or math.py for your own files.
  • Running work during import

    Put script startup code behind if __name__ == "__main__".
  • Circular imports

    Move shared logic into a third module or redesign the dependency direction.

Try this next

Split a Script Into Files

0 of 2 completed

  1. Move two helper functions into helpers.py and import them from main.py.
  2. Create a bad json.py name, observe the import problem, then rename it safely.

Questions About Module

A module is usually one .py file. A package is a folder of modules that Python can import as a group.

Python executes a module the first time it imports it. Keep direct script actions behind if __name__ == "__main__".

Move shared code to a third module, reduce import-time work, or import inside a function only when needed.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.