What is Moudule ?
M3-R5.1 · Chapter 8: Scope and Modules · 3 min read
What is Module?
A module is a .py file containing Python definitions and statements (functions, classes, variables). Modules allow you to organize and reuse code across multiple programs.
- File Extension: Every Python module is a .py file
- Purpose: Code reuse, organization, namespace separation
- Built-in Modules: math, os, sys, random, datetime, json, etc.
- Custom Modules: Any .py file you create yourself
Why Use Modules?
- Avoid repeating code across multiple programs
- Organize large programs into manageable separate files
- Share code between different projects
- Use Python's rich standard library of ready-made tools
- Prevent name conflicts using separate namespaces
Importing a Module — import Statement
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
Note: After 'import math', all names must be accessed with dot notation: math.function_name()
from...import Statement
from math import pi, sqrt
print(pi) # 3.141592... (no need to write math.pi)
print(sqrt(25)) # 5.0
Importing with Alias — as keyword
import numpy as np # Common alias in data science
from math import factorial as fact
print(fact(6)) # 720
from...import * (Import Everything)
from math import *
print(sin(0)) # 0.0
print(cos(0)) # 1.0
Note: 'from module import *' is discouraged in large programs as it pollutes the namespace and makes it hard to trace where names come from.
Import Styles — Comparison
|
Import Style |
Syntax |
Access Style |
Use Case |
|
Full module |
import math |
math.sqrt() |
Avoid name conflicts |
|
Specific names |
from math import sqrt |
sqrt() |
Frequently used functions |
|
With alias |
import math as m |
m.sqrt() |
Shorten long module names |
|
All names |
from math import * |
sqrt() |
Quick scripts only |
What is Namespace?
A namespace is a container that holds a collection of names and their associated objects. Every module has its own namespace — names in one module do NOT clash with names in another module.
How Modules Create Namespaces
When you import a module, Python executes the module file and creates a module namespace.
All names defined in that file become attributes of the module object.
# mymodule.py
x = 100
def greet():
print('Hello from mymodule!')
# main.py
import mymodule
print(mymodule.x) # 100
mymodule.greet() # Hello from mymodule!
Note: mymodule.x accesses name x inside mymodule's namespace — no collision even if you also have a variable named x in your own program.