Importing and Using Modules

Loading

Modules in Python allow you to organize code into separate files, making it reusable and maintainable. A module is simply a Python file (.py) that contains functions, classes, and variables that can be used in other Python programs.


1. Types of Modules in Python

Python provides three types of modules:
Built-in Modules – Pre-installed with Python (e.g., math, random, os)
User-Defined Modules – Custom modules created by the user
External Modules – Third-party modules installed via pip (e.g., numpy, requests)


2. Importing Modules

Python provides different ways to import modules:

2.1 Importing the Entire Module

import math

print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793

Access functions using module_name.function_name()

2.2 Importing Specific Functions from a Module

from math import sqrt, pi

print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793

No need to use math. prefix when calling functions

2.3 Importing a Module with an Alias

import numpy as np

arr = np.array([1, 2, 3])
print(arr) # Output: [1 2 3]

Shortens the module name for convenience

2.4 Importing All Functions from a Module (*)

from math import *

print(sin(0)) # Output: 0.0
print(log(10)) # Output: 2.302585092994046

Not recommended – Can cause conflicts with other function names.


3. Creating and Importing User-Defined Modules

You can create your own module and import it into another script.

3.1 Creating a Custom Module (mymodule.py)

# mymodule.py
def greet(name):
return f"Hello, {name}!"

def add(a, b):
return a + b

3.2 Importing and Using the Module

import mymodule

print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.add(5, 3)) # Output: 8

3.3 Importing Specific Functions

from mymodule import greet

print(greet("Bob")) # Output: Hello, Bob!

4. Using dir() to List Module Contents

The dir() function lists all functions and variables in a module.

import math
print(dir(math))

🔍 Output (Partial List)

['acos', 'asin', 'atan', 'ceil', 'cos', 'degrees', 'e', 'exp', 'factorial', 'floor', 'log', 'pi', 'pow', 'radians', 'sin', 'sqrt', 'tan']

5. Importing External Modules

External modules are installed using pip (Python package manager).

5.1 Installing an External Module

Example: Installing requests module

pip install requests

5.2 Using an External Module

import requests

response = requests.get("https://api.github.com")
print(response.status_code) # Output: 200

6. Understanding __name__ and __main__

In Python, every module has a built-in variable __name__.

  • If a module is run directly, __name__ is set to "__main__".
  • If a module is imported, __name__ is set to the module’s filename.

6.1 Example (mymodule.py)

# mymodule.py
def greet(name):
return f"Hello, {name}!"

if __name__ == "__main__":
print(greet("Alice")) # Runs only when executed directly

6.2 Running mymodule.py Directly

$ python mymodule.py
Hello, Alice!

6.3 Importing mymodule.py into Another Script

import mymodule
print(mymodule.greet("Bob"))

Output: Only "Hello, Bob!" is printed, since the if __name__ == "__main__": block is ignored when imported.


7. Reloading a Module (importlib)

If you modify a module and want to reload it without restarting Python, use importlib.reload().

import mymodule
import importlib

importlib.reload(mymodule)

8. Finding Module Location

To find where a module is installed, use:

import os
print(os.__file__) # Output: /usr/lib/python3.10/os.py

9. Summary

Import TypeSyntaxExample
Import entire moduleimport module_nameimport math
Import specific function(s)from module import funcfrom math import sqrt
Import with aliasimport module as aliasimport numpy as np
Import all functions (not recommended)from module import *from math import *
Reload a moduleimportlib.reload(module)importlib.reload(mymodule)

Leave a Reply

Your email address will not be published. Required fields are marked *