Back to Python
2026-03-295 min read

Video: Python Packages: Organize Your Code

Learn Video: Python Packages: Organize Your Code step by step with clear examples and exercises.

Title: Video: Python Packages - Organize Your Code

Why This Matters

In this lesson, we delve into Python packages, an essential tool for organizing and managing code effectively. By mastering Python packages, you will be better equipped to handle complex projects, collaborate with other developers, and avoid common pitfalls that can hinder your workflow. This knowledge is crucial for excelling in coding interviews, real-world programming tasks, and even debugging issues that may arise during project development.

Prerequisites

To fully comprehend this lesson, you should have a strong understanding of Python fundamentals, including variables, functions, loops, and conditional statements. Familiarity with the command line or integrated development environments (IDEs) like PyCharm and Visual Studio Code will also be helpful.

Understanding Directories and Modules

Before diving into packages, it's essential to understand how Python organizes code within directories and modules. A directory (or folder) can contain one or more Python files (modules), which can be imported and used in other scripts.

Importing Modules

To import a module, you use the import statement followed by the name of the module:

import my_module

You can then access functions or variables defined within that module using dot notation:

result = my_module.my_function()

Core Concept

Python packages are collections of modules, scripts, and data that can be installed and imported to extend Python's functionality. They help organize code into reusable components, making it easier to manage large projects and collaborate with other developers.

Installing a Package

To install a package, you can use the pip command in your terminal or command prompt:

pip install <package_name>

Replace `` with the name of the package you want to install. For example:

pip install requests

Importing a Package

Once installed, you can import a package into your Python script using the import statement:

import <package_name>

For instance:

import requests

Using a Package

After importing a package, you can access its functions and classes. For example, the requests package allows you to send HTTP requests from your Python scripts:

import requests

response = requests.get('https://www.google.com')
print(response.text)

Organizing Your Code with Packages

By creating and managing packages, you can keep your code organized and modular. For example, you might create a package for a specific project or library of related functions:

mkdir my_project
cd my_project
python -m venv .venv
source .venv/bin/activate
pip install my_package
touch my_package/__init__.py
touch my_package/my_function.py

In my_package/my_function.py, you can define and export a function:

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

__all__ = ['greet']

Then, in another Python script within the my_project directory, you can import and use this function:

import my_package

print(my_package.greet('World'))

Installing Third-Party Packages

Python's Package Index (PyPI) hosts thousands of third-party packages that you can install with pip. Some popular ones include:

  • requests for sending HTTP requests
  • numpy and scipy for numerical computing
  • matplotlib and seaborn for data visualization
  • flask and django for web development

Worked Example

In this example, we'll create a simple package that defines a function to generate Fibonacci numbers. We'll also add tests to ensure the function works correctly.

  1. Create the package directory:
mkdir fibonacci_package
cd fibonacci_package
python -m venv .venv
source .venv/bin/activate
pip install -e .
touch __init__.py
touch fibonacci.py
touch tests/test_fibonacci.py
  1. Define the Fibonacci function in fibonacci.py:
def fib(n):
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)

__all__ = ['fib']
  1. Define tests for the Fibonacci function in tests/test_fibonacci.py:
import unittest
from fibonacci import fib

class TestFibonacci(unittest.TestCase):
def test_small_numbers(self):
self.assertEqual(fib(1), 1)
self.assertEqual(fib(2), 1)
self.assertEqual(fib(3), 2)
self.assertEqual(fib(4), 3)
self.assertEqual(fib(5), 5)

def test_large_numbers(self):
self.assertEqual(fib(10), 55)
self.assertEqual(fib(20), 6765)
self.assertEqual(fib(30), 832040)
self.assertEqual(fib(40), 3439887136)

if __name__ == '__main__':
unittest.main()
  1. Run the tests:
python -m unittest discover tests

The tests should pass, indicating that our Fibonacci function works correctly for small and large numbers.

Common Mistakes

1. Forgetting to activate the virtual environment

When working with packages, it's essential to activate the virtual environment before installing or using packages:

source .venv/bin/activate
pip install <package_name>

2. Importing a package incorrectly

Ensure that you import the correct package and use the appropriate syntax:

import requests # Correct
from requests import get # Incorrect; only imports the 'get' function, not other functions or classes

3. Not installing a package in the correct directory

When creating a new package, make sure to navigate to its directory before running pip install -e .. This ensures that the package is installed in the correct location.

4. Ignoring tests

Writing and running tests is an essential part of developing packages. Tests help ensure that your code works correctly and catches bugs early on.

Practice Questions

  1. Create a simple package for converting temperatures between Celsius and Fahrenheit. Define functions for both conversion directions. Include tests to verify the correctness of your conversions.
  2. Install and use the numpy package to perform matrix multiplication. Write a script that defines two 3x3 matrices, multiplies them using numpy's matrix multiplication function, and prints the result.
  3. Write a Python script that sends an HTTP GET request to the Google search API and prints the top 10 results for a specific query. Use the requests package for sending the request.

FAQ

Q: Why should I create my own packages?

A: Creating your own packages helps keep your code organized, modular, and reusable. It also makes it easier for other developers to collaborate with you on projects. Additionally, publishing your package on PyPI can help establish your reputation as a developer in the Python community.

Q: How do I uninstall a package?

A: To uninstall a package, use the following command in your terminal or command prompt:

pip uninstall <package_name>

Q: What is the difference between pip install and pip install -e?

A: pip install installs a package globally, while pip install -e . installs a package in editable mode, allowing you to make changes to the package directly from your project directory. When you use -e, any changes you make to the package will be reflected immediately without having to reinstall the package.

Q: How do I publish my own Python package on PyPI?

A: To publish a package on PyPI, follow these steps:

  1. Create a new directory for your package and navigate to it in the terminal.
  2. Initialize a new virtual environment and activate it.
  3. Install setuptools, wheel, and twine using pip.
  4. Create a setup.py file with the necessary metadata, dependencies, and package structure information.
  5. Build and test your package locally.
  6. Tag your Git repository with a version number.
  7. Use twine to upload your package to PyPI:
twine upload dist/*

This will upload the packaged files (.whl or .tar.gz) to PyPI, making them available for other developers to install using pip.

Video: Python Packages: Organize Your Code | Python | XQA Learn