Skip to main content

1. What is a Module?

A module is simply a Python file (with a .py extension) containing variables, functions, or classes that you want to reuse in other parts of your program.

Creating and Importing a Module

Suppose we create a file named calculator.py:
Now, we can use these functions in another file (e.g., main.py) in the same folder by importing it:

2. What is a Package?

A package is a directory (folder) that contains multiple modules. It allows you to organize related modules hierarchically.

The Role of __init__.py

To turn a standard folder into a Python package, it must contain a file named __init__.py. This file does several things:
  1. Marks Directories: It tells Python that this directory is an importable package.
  2. Initialization Code: Python executes __init__.py first when the package or any sub-module is imported.
  3. Creates Public APIs: You can import sub-modules inside __init__.py to make them accessible directly from the package root:
    Now consumers can write:
  4. Controls Wildcard Imports: Define a list called __all__ to restrict what gets imported when someone uses from package import *:

3. Python’s Standard Library Essentials

Python follows a “batteries included” philosophy, providing powerful built-in modules that are ready to use immediately.

A. The pathlib Module

Modern Python uses pathlib for object-oriented filesystem paths:

B. The os Module

Used for interacting with the operating system:

C. The datetime Module

Provides classes for manipulating dates and times:

D. The uuid Module

Generates RFC 4122 compliant universally unique identifiers (UUIDs):

E. The json Module

JSON is the standard data format for web APIs. Python’s json module parses and serializes JSON:

4. Third-Party Packages (e.g., requests)

While the Standard Library provides urllib for handling HTTP requests, the community standard is the third-party requests library due to its clean, human-readable API. To use it, you must first install it within your virtual environment:

Making HTTP Requests

Here is how you can perform typical GET and POST operations using requests: