Python Packages – Understanding Packages

Learn Python @

In the realm of Python programming, understanding packages is essential for organizing and managing code in larger projects. In this comprehensive guide, we will delve deep into packages in Python, providing detailed explanations, real-world examples, and practical use cases, complete with code snippets and outputs. By the end, you’ll have a solid understanding of packages, subpackages, and how to use them to structure your Python projects effectively.

Introduction to Packages

In Python, a package is a way to organize related modules into a directory hierarchy. Packages help you manage and structure your code in a clean and organized manner, making it more manageable and maintainable, especially in large projects.

Creating Packages

To create a package, you need to follow these steps:

  1. Create a Directory: Create a directory (folder) with a name that will serve as the package name. This directory should also contain a special file named This file can be empty or can contain initialization code for the package.
  2. Add Modules: Inside the package directory, you can add Python module files (.py) that contain your code.


Let’s create a simple package named my_package with two modules, and



def greet(name):
    return f"Hello, {name}!"


def calculate_square(x):
    return x * x

Importing from Packages

You can import modules from a package using dot notation. For example, to import the greet function from module1 within the my_package package:

from my_package.module1 import greet
message = greet("Alice")
print(message)  # Output: Hello, Alice!


Packages can also contain subpackages, creating a hierarchical structure for your code. To create a subpackage, you can simply create a subdirectory within a package directory and add its own file.


Let’s add a subpackage named sub_pkg to our my_package package:


In this structure, you can import modules from the subpackage using dot notation, just like with regular packages.

Author: user