#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
•Question 10 of 41easy

Modules in Python

Importing and using modules.

What You'll Learn

  • What modules are and why they're important
  • Different import styles and when to use each
  • Creating your own modules
  • Understanding packages and init.py
  • Essential built-in modules

Understanding Modules

A module is a file containing Python code (functions, classes, variables) that can be imported and reused in other Python files. Modules help organize code, promote reusability, and avoid naming conflicts.

Python's ecosystem strength comes from its vast collection of modules - both built-in and third-party (via pip).

Import Styles

code.pyPython
# 1. Import entire module
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.14159...

# 2. Import specific items
from math import sqrt, pi
print(sqrt(16))  # 4.0 (no prefix needed)
print(pi)

# 3. Import with alias
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 4. Import all (avoid - pollutes namespace)
from math import *  # Not recommended!

# 5. Rename specific import
from datetime import datetime as dt
now = dt.now()

Which Style to Use?

StyleWhen to Use
import moduleLarge modules, clear namespace
from module import xFew specific functions needed
import module as aliasLong names, conventions (np, pd)
from module import *Almost never (testing only)

Creating Your Own Modules

code.pyPython
# myutils.py
"""My utility functions module."""

PI = 3.14159

def greet(name):
    """Return a greeting message."""
    return f"Hello, {name}!"

def calculate_area(radius):
    """Calculate circle area."""
    return PI * radius ** 2

class Calculator:
    def add(self, a, b):
        return a + b
code.pyPython
# main.py
import myutils

print(myutils.greet("Alice"))
print(myutils.PI)
print(myutils.calculate_area(5))

calc = myutils.Calculator()
print(calc.add(2, 3))

The name Variable

code.pyPython
# mymodule.py
def main():
    print("Running as main script")

# Only runs when executed directly, not when imported
if __name__ == "__main__":
    main()

Packages (Module Folders)

code.txtTEXT
mypackage/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ module1.py
ā”œā”€ā”€ module2.py
└── subpackage/
    ā”œā”€ā”€ __init__.py
    └── module3.py
code.pyPython
# Importing from packages
from mypackage import module1
from mypackage.module2 import some_function
from mypackage.subpackage import module3

# __init__.py can expose package-level imports
# In mypackage/__init__.py:
from .module1 import func1
from .module2 import func2

Essential Built-in Modules

code.pyPython
# os - Operating system interface
import os
os.getcwd()           # Current directory
os.listdir(".")       # List files
os.path.exists("f")   # Check if exists
os.makedirs("dir")    # Create directories

# sys - System-specific parameters
import sys
sys.version           # Python version
sys.path              # Module search paths
sys.argv              # Command line arguments

# datetime - Date and time
from datetime import datetime, timedelta
datetime.now()        # Current datetime
datetime.strptime("2024-01-15", "%Y-%m-%d")

# json - JSON encoding/decoding
import json
json.dumps({"a": 1})  # Dict to JSON string
json.loads('{"a":1}') # JSON string to dict

# random - Random numbers
import random
random.randint(1, 10)
random.choice([1, 2, 3])
random.shuffle(list)

# re - Regular expressions
import re
re.search(r"\d+", "abc123")
re.findall(r"\w+", "hello world")

Interview Tip

When asked about Python modules:

  1. Module = Python file with reusable code
  2. import math vs from math import sqrt - namespace clarity
  3. Use if __name__ == "__main__" for script entry points
  4. Packages are folders with __init__.py
  5. Know common modules: os, sys, json, datetime, re