SyntaxStudy
Sign Up
Python Creating Your Own Modules
Python Beginner 8 min read

Creating Your Own Modules

Creating Your Own Modules

Any Python file is a module. You can import it from other files in the same directory (or package).

mathutils.py

# mathutils.py
"""Utility math functions."""

PI = 3.14159265358979

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

def is_prime(n):
    """Return True if n is prime."""
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

if __name__ == "__main__":
    # Only runs when executed directly, not when imported
    print(circle_area(5))
    print(is_prime(17))

Using the Module

# main.py
import mathutils
print(mathutils.circle_area(5))   # 78.539...
print(mathutils.is_prime(17))     # True
print(mathutils.PI)

__name__ Guard

if __name__ == "__main__":
    # This block runs only when the file is executed directly
    # NOT when imported as a module
    main()

__all__ for Public API

# Define what 'from module import *' exports
__all__ = ["circle_area", "is_prime"]
Example
# Inline module simulation
import types

mathutils = types.ModuleType("mathutils")
mathutils.PI = 3.14159
mathutils.circle_area = lambda r: mathutils.PI * r**2
mathutils.is_prime = lambda n: n > 1 and all(n % i for i in range(2, int(n**0.5)+1))

print(mathutils.circle_area(5))
print(mathutils.is_prime(13))
print(mathutils.is_prime(15))
Pro Tip

The if __name__ == "__main__": guard is a Python idiom that lets a file serve as both a reusable module and a runnable script.