Python Modules

In Python, a module is a file containing Python definitions, functions, and statements. Modules allow you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is simply a Python file with a .py extension, which can be imported and utilized in other Python programs.

Importing a Module

To use the functions or variables defined in a module, you need to import that module using the import statement. Once a module is imported, you can access its contents using the module's name.

1. Importing a Built-in Module


import math
# Using functions from the math module
print("Square root of 16 is:", math.sqrt(16))
print("Value of Pi is:", math.pi)
            

Output

Square root of 16 is: 4.0 Value of Pi is: 3.141592653589793

Creating a Custom Module

You can create your own modules by saving functions and variables in a Python file with a .py extension. Let's create a custom module named mymodule.py and use it in another Python file.

2. Creating and Using a Custom Module


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

# Using the custom module
import mymodule
print(mymodule.greet("Alice"))
            

Output

Hello, Alice!

Using from ... import Statement

You can import specific functions or variables from a module using the from ... import statement. This allows you to access the imported items directly without using the module name.

3. Importing specific functions from the math module


from math import sqrt, pi

print("Square root of 25 is:", sqrt(25))
print("Value of Pi is:", pi)
            

Output

Square root of 25 is: 5.0 Value of Pi is: 3.141592653589793

Using the dir() Function

The dir() function is used to find all the names defined in a module. It returns a sorted list of strings containing the names of all the functions, variables, and classes in the module.

4.


import math

print(dir(math))
            

Output

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', ...]

Reloading a Module

Python modules are cached after being imported. If you modify a module's code, you need to reload it using the reload() function from the importlib module.

5.


import mymodule
from importlib import reload

# Modify mymodule.py and then reload it
reload(mymodule)
            

Output

(Module reloaded successfully)

Python modules are a powerful way to organize and reuse code across multiple programs. You can use built-in modules or create your own custom modules for specific tasks. Modules help you keep your code clean, organized, and efficient.