Python Modules

Python modules allow you to organize code by splitting large programs into smaller files. A module is simply a Python file (.py) containing reusable functions, variables, or classes.

Modules help keep code structured, maintainable, and easier to debug.

Why Use Modules

odules are helpful because they:

  • Improve code reusability
  • Keep large programs organized
  • Make debugging and maintenance easier
  • Allow you to share functions across multiple files

A module works like a toolbox—each tool (function) is stored once and reused whenever needed.

Creating a Module

A module is just a .py file.
Here is an example module named fibo.py:

# Fibonacci numbers module

def fib(n):    # Print Fibonacci series up to n
   a, b = 0, 1
   while a < n:
       print(a, end=' ')
       a, b = b, a + b
   print()

def fib2(n):   # Return Fibonacci series up to n
   result = []
   a, b = 0, 1
   while a < n:
       result.append(a)
       a, b = b, a + b
   return result

This module defines two functions: fib() and fib2().

Importing a Module

Use the import statement to load a module:

import fibo

This imports the module but does not bring its functions into the current namespace.

Using Module Functions

Call a function inside the module using:

import fibo
fibo.fib(1000)

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

To get the module name:

fibo.__name__

Assigning a Local Alias

If you frequently call the same function, assign it a local name:

import fibo
fib = fibo.fib
fib(500)

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This makes the code shorter and easier to read.

Module Namespace and Scope

  • Each module has its own private namespace.
  • Variables and functions defined inside a module do not interfere with variables in another script.
  • Access items using the notation:
    module_name.item_name

This keeps code organized and prevents name conflicts.

Importing Specific Functions

You can import only selected functions from a module:

from fibo import fib, fib2
fib(500)
 

This keeps the current namespace clean because only selected names are imported.

Importing Everything (*)

from fibo import *
fib(500)

This imports all functions and variables that do not begin with _.

Note: Avoid this in large projects because it can cause name conflicts.

Renaming Imported Functions

Rename a specific function during import:

from fibo import fib as fibonacci
fibonacci(500)

Helpful when different modules have functions with the same name.

Reloading a Module

Python loads a module only once per session.
If you update the code inside the module, reload it manually:

import fibo
import importlib
importlib.reload(fibo)

This reloads the updated version of the module.

Executing a Module as a Script

A module can be executed directly as a standalone script:

python fibo.py 50  

To support script execution and module import inside the same file, include:

if __name__ == "__main__":
   import sys
   fib(int(sys.argv[1]))

When run directly → __name__ becomes "__main__"

When imported → __name__ becomes "fibo"

Module Search Path

When Python executes:

import spam

It searches for the module in this order:

  • Built-in modules
  • The current script directory
  • Directories listed in sys.path
  • Site-packages folder

To view the search path:

import sys
print(sys.path)

To add a new directory:

sys.path.append("/new/module/path")

Compiled Python Files (.pyc)

To speed up loading, Python compiles modules into bytecode and stores them in:

__pycache__/module.cpython-310.pyc

How it works:

  • Python checks if a .pyc file exists
  • If out of date → Python recompiles
  • These compiled files are platform-independent

To compile all modules manually:

python -m compileall .

Optimized compilation:

python -O script.py
python -OO script.py

-O removes assert
-OO removes assert + docstrings

Standard Python Modules

Python provides a large number of built-in modules such as:

  • sys
  • os
  • math
  • json
  • random

These modules add system access, math operations, file handling, and much more.

Built-in modules are available immediately.
External modules need installation using pip.

The sys Module

The sys module provides access to Python interpreter settings and system information.

Customizing prompts (for interactive sessions):

import sys
print(sys.ps1)
sys.ps1 = "C> "
 

Adding new module search paths:

import sys
sys.path.append("/ufs/guido/lib/python")

This lets Python search additional locations for modules.

The dir() Function

The dir() function lists all names available in a module.

import fibo
import sys

print(dir(fibo))
print(dir(sys))

Checking current namespace:

a = [1, 2, 3]
import fibo
fib = fibo.fib

print(dir())

Listing built-in names:

import builtins
print(dir(builtins))

This helps you understand what functions or variables are available.