Back to Study Material Python

Modules

A module in Python is simply a file containing Python code. It can define functions, classes, and variables, and it can also include runnable code. The mai...

Modules

Python Modules: Organizing Code into Reusable Files

A module in Python is simply a file containing Python code. It can define functions, classes, and variables, and it can also include runnable code. The main purpose of modules is to organize code into logical units that can be reused across multiple programs without copying and pasting.

When you write a non-trivial Python program, you typically split it into multiple files. Each file is a module. You use the import statement to bring code from one module into another:

# In math_helpers.py def square(n): return n * n

def cube(n): return n * n * n

# In main.py import math_helpers print(math_helpers.square(4)) # 16 print(math_helpers.cube(3)) # 27

You can also import specific names from a module with from ... import ..., which lets you use them without the module prefix:

from math_helpers import square, cube print(square(4)) # 16

The as keyword creates an alias, which is useful for long module names or to avoid name conflicts:

import math_helpers as mh print(mh.square(5)) # 25

When Python imports a module, it executes all the top-level code in that file. This is why it is good practice to place runnable code inside an if __name__ == "__main__": block. This block only runs when the file is executed directly, not when it is imported as a module. Without this guard, your test code and script logic would run every time another module imports your file.

# math_helpers.py if __name__ == "__main__": print(square(6)) # only runs when executed directly

Python caches imported modules in sys.modules. The second time you import the same module, Python uses the cached version rather than re-executing the file. This is why modifying a module and reimporting it in the same session does not always reflect your changes without restarting the interpreter.

Exam tip: The __name__ variable is set to "__main__" when a file is run directly and to the module's filename (without .py) when it is imported. This is a fundamental Python idiom that appears in almost every real-world script and is a common exam topic.