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"]