Python Modules

Learn how to create, import, and use modules in Python to organize and reuse your code.

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example - Save this code in a file named mymodule.py:

def greeting(name):
    print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example - Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example - Save this code in the file mymodule.py:

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Example - Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example - Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example - Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

Example - List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example - The module named mymodule has one function and one dictionary:

def greeting(name):
    print("Hello, " + name)

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Example - Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"]

Import All

You can import all names from a module by using the * wildcard:

Example - Import all names from mymodule:

from mymodule import *

greeting("Jonathan")
print(person1["age"])

Note: It's generally not recommended to use import * as it can lead to namespace pollution.

Module Search Path

Python looks for modules in several locations:

Example - Check the module search path:

import sys

for path in sys.path:
    print(path)
  • Current directory
  • PYTHONPATH environment variable directories
  • Standard library directories
  • Site-packages directory

Creating Packages

A package is a collection of modules in directories that give structure to your code:

Example - Package structure:

mypackage/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        module3.py

Example - __init__.py file:

# mypackage/__init__.py
from .module1 import function1
from .module2 import function2

__all__ = ['function1', 'function2']

Example - Using the package:

import mypackage
from mypackage import module1
from mypackage.subpackage import module3

# Use functions
mypackage.function1()
module1.function1()
module3.some_function()

Module Documentation

Good modules should include documentation:

Example - Well-documented module:

"""
Math utilities module.

This module provides various mathematical utility functions
for common calculations.
"""

import math

def calculate_area_circle(radius):
    """
    Calculate the area of a circle.
    
    Args:
        radius (float): The radius of the circle
        
    Returns:
        float: The area of the circle
        
    Raises:
        ValueError: If radius is negative
    """
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

def calculate_distance(x1, y1, x2, y2):
    """
    Calculate the distance between two points.
    
    Args:
        x1, y1 (float): Coordinates of first point
        x2, y2 (float): Coordinates of second point
        
    Returns:
        float: The distance between the points
    """
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

# Module-level constants
PI = math.pi
E = math.e

Common Built-in Modules

os

Operating system interface

import os
print(os.getcwd())
os.mkdir('new_folder')

sys

System-specific parameters

import sys
print(sys.version)
sys.exit()

datetime

Date and time handling

import datetime
now = datetime.datetime.now()
print(now)

random

Generate random numbers

import random
print(random.randint(1, 10))
print(random.choice(['a', 'b', 'c']))

json

JSON encoder and decoder

import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)

urllib

URL handling modules

import urllib.request
response = urllib.request.urlopen('http://example.com')

Best Practices

  • Use descriptive module names
  • Keep modules focused on a single purpose
  • Include docstrings for modules and functions
  • Use if __name__ == "__main__": for executable scripts
  • Avoid circular imports
  • Use relative imports within packages

Example - Module with main guard:

"""Calculator module with basic operations."""

def add(a, b):
    """Add two numbers."""
    return a + b

def subtract(a, b):
    """Subtract two numbers."""
    return a - b

def main():
    """Main function for testing."""
    print("Testing calculator module")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"5 - 3 = {subtract(5, 3)}")

if __name__ == "__main__":
    main()

Import Styles

StatementUse
import mathmath.sqrt(9)
import math as mm.sqrt(9) (alias)
from math import sqrtsqrt(9) (specific name)
from math import *Everything (avoid — pollutes namespace)

Avoid from module import * — it hides where names come from and can silently overwrite your variables.

Your Own Module and __main__

# mymath.py
def add(a, b):
    return a + b

if __name__ == "__main__":     # runs only when executed directly
    print("testing:", add(2, 3))

# other.py
import mymath
print(mymath.add(10, 5))       # 15  -> the guard block does NOT run

The if __name__ == "__main__" guard lets a file act as both an importable module and a runnable script.

Try It Yourself

Exercise 1: Import only pi from math and print it.

Show solution
from math import pi
print(pi)   # 3.141592653589793

Exercise 2: Use dir() to list what a module provides.

Show solution
import random
print([n for n in dir(random) if not n.startswith("_")][:5])

Key Takeaways

  • Modules are .py files you import to reuse code.
  • Import specific names, or the whole module with an alias.
  • Guard runnable code with if __name__ == "__main__".
  • Explore a module with dir() and help().

📘 Real-World Deep Dive

Modules are how Python code is shared and reused. The proper module pattern — a top-level <code>if __name__ == "__main__":</code> guard, typed public API, and minimal hidden globals — is the foundation of any maintainable codebase.

Real-Life Scenario

A small, well-structured package with two modules, a CLI entry point, and a clean import story.

Real-Life Example

# demo:  tiny package layout
# mypkg/
#   __init__.py
#   validation.py
#   service.py
#   __main__.py

# validation.py
from dataclasses import dataclass
from typing import Iterable

@dataclass(frozen=True)
class Email:
    address: str
    def __post_init__(self):
        if "@" not in self.address:
            raise ValueError(f"not an email: {self.address!r}")

def valid_emails(addresses: Iterable[str]) -> list[Email]:
    return [Email(a) for a in addresses if "@" in a]

# service.py
from .validation import Email
def send_greeting(recipients: list[Email], subject: str = "Hello") -> int:
    print(f"preparing to send {len(recipients)} emails with subject {subject!r}")
    return len(recipients)

# __main__.py
from .validation import valid_emails
from .service import send_greeting

def main() -> int:
    raw = ["ada@example.com", "broken", "cy@example.com"]
    recipients = valid_emails(raw)
    return send_greeting(recipients, subject="Welcome")

if __name__ == "__main__":
    raise SystemExit(main())

Expected Output

preparing to send 2 emails with subject 'Welcome'

Common mistakes

  • Importing at module-level triggers all top-level code — expensive imports can hurt startup latency.
  • Circular imports crash at module load — refactor shared bits into a third module.
  • Wildcard from x import * pollutes the namespace; always import explicit names.

🚀 Performance & Best Practices

  • Lazy-import heavy modules (pandas, torch) inside functions to keep startup fast.
  • Build a public API in __init__.py by re-exporting; keep internal helpers underscore-prefixed.
  • Cache expensive module imports at function scope: def f(): import pandas as pd; ....

🧪 Try It Yourself

  1. Add a pyproject.toml with [project] metadata and a console_scripts entry point.
  2. Move valid_emails into a mypkg.validation subpackage with one pure-helper per file.
  3. Profile import time across cold imports with python -X importtime.

FAQ: Python Modules

Common questions about this page.

What is Python Modules?

Python Modules is a Python Tutorial lesson that explains python modules in Python. Learn how to create, import, and use modules in Python to organize and reuse your code. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python modules examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python modules in this Python Tutorial Python lesson (Python Modules).

How do I use python modules in Python?

To use python modules in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python modules?

This Python Modules tutorial shows python modules syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Modules example for beginners

Yes. This page includes a beginner python modules example you can copy and run. It is designed for searches such as "python modules for beginners", "python modules example", and "how to use python modules".

What are common mistakes with python modules?

Common python modules mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python modules?

Python Modules is used in real Python work. Learning python modules helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Modules free to learn online?

Yes. You can learn python modules free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.