Introduction to Modules

3 min read ·

What is a Module?

A module in Python is a file that contains reusable Python code.
This code can include:
  • Functions
  • Variables
  • Classes
  • Executable statements
Instead of writing everything in a single file, code is divided into smaller files called modules to improve structure and reuse.

Why Use Modules?

  • Makes code reusable
  • Improves readability
  • Helps manage large applications
  • Reduces duplication
Note

Modules help in organizing code logically by separating functionality into different files.


Importing Modules

Basic Import

Access module elements using the dot operator.

Import with Alias

Alias helps in writing shorter and cleaner code.

Import Specific Functions

No need to use module name prefix.

Import Everything

Caution

Avoid using import * in large projects because it can create naming conflicts and reduce code clarity.


How Python Finds Modules

When importing a module, Python searches in:
  1. Current directory
  2. Built-in modules
  3. Installed packages

Built-in Modules Examples

math module


random module


datetime module


Pro Tip

Use dir(module_name) to explore available functions and attributes inside a module.


Creating Your Own Module

Step 1: Create a file

File name: my_module.py

Step 2: Import and use it


Using Alias with Custom Module


name Variable

  • If file is executed directly, value is main
  • If imported, value is module name
This ensures certain code runs only when the file is executed directly.

Real World Scenario

In real applications, modules are created for different functionalities like authentication, database handling, and API logic to keep the system organized.


Common Mistakes

Stop
  • Naming a file same as a built-in module like math.py
  • Incorrect file location
  • Circular imports between modules

Exercise

Create a module named calculator.py:
  • Add function for addition
  • Add function for subtraction
Import it in another file and use both functions.