Importing Modules

Modules are Python files containing reusable code, such as functions, classes, and variables. They allow you to organize and reuse code across different parts of a project or multiple projects.

To use a module, you need to import it into your Python script using the import statement.

import math
x = math.sqrt(16)  # x = 4.0
y = math.pi  # y = 3.141592653589793

Writing Modules

You can create your own modules by writing Python code in a separate file with a .py extension. Then, you can import and use the functions, classes, or variables defined in that module.

For example, create a file called my_module.py with the following content:

# my_module.py
def greet(name):
print(f"Hello, {name}!")
pi = 3.14159

Then, in your main script, you can import and use the module:

import my_module
my_module.greet("Alice")  # Output: Hello, Alice!
print(my_module.pi)  # Output: 3.14159

Packages

Packages are collections of modules organized in a directory hierarchy. They provide a way to structure and organize related modules together, making it easier to manage large codebases.

To create a package, you need to have a directory with an __init__.py file, which can be empty or contain initialization code for the package.

For example, let's create a package called my_package with two modules: module1.py and module2.py. The directory structure would look like this:

import my_package.module1
my_package.module1.my_function()

Alternatively, you can import specific modules or objects from the package:

from my_package import module1
module1.my_function()
from my_package.module2 import my_class
obj = my_class()

The Python Standard Library

Python comes with a vast standard library containing numerous built-in modules that provide a wide range of functionality, such as file handling, networking, data manipulation, and more. Some commonly used modules include os, sys, math, re, datetime, and json.

You can import and use these modules directly in your Python scripts without the need for any additional installation.

import os
import datetime
current_dir = os.getcwd()
today = datetime.date.today()

 

In the next chapter, we'll explore file handling in Python, which allows you to read from and write to files on your local filesystem or remote locations.