Python Package

1. What is a Package

A package is a collection of Python modules organized in a directory hierarchy, enabling structured and scalable code organization.

Example structure:

my_package/
│── __init__.py
│── module1.py
│── module2.py

The presence of __init__.py indicates that the directory is a Python package.


2. Creating a Basic Package

# my_package/module1.py
def greet():
    return "Hello from module1"
# main.py
import my_package.module1

print(my_package.module1.greet())

Packages allow logical grouping of related modules.


3. Importing from a Package

Enables direct access to specific functions or classes within a package.


4. Using init.py for Initialization

__init__.py controls what gets exposed when the package is imported.


5. Sub-packages Structure

Packages can contain nested sub-packages for large systems.


6. Relative Imports Inside a Package

Relative imports use:

  • . current package

  • .. parent package

Ensures internal module cohesion.


7. Absolute Imports in Packages

Preferred in production for clarity and maintainability.


8. Installing External Packages with pip

External packages extend Python's functionality.


9. Viewing Installed Packages

Displays all packages installed in the Python environment.


10. Packaging a Custom Project (Setup File)

This enables distribution and installation of your package via PyPI or internal repositories.


Last updated