Overview

Python packages are an essential aspect of organizing and structuring your codebase, especially when you are dealing with large-scale projects or complex functionalities. In this comprehensive guide, we will walk you through the process of creating your first Python package based on the directory structure provided.

Understanding the Directory Structure

Python Package directory structure

Before diving into creating the package, let's understand the directory structure you already have. The robot_beejok directory serves as the main package, and it contains two subpackages - movement and rotation. Each subpackage contains modules with specific functionalities related to robot movement and rotation.

The robot_beejok package is designed to handle various aspects of robot movement and rotation. It is structured in a hierarchical manner with different modules organized into subdirectories based on their functionalities. Here's a brief overview of each component:

This directory structure provides a well-organized way to manage various aspects of robot movement and rotation, making it easier to maintain and extend the functionality of the robot_beejok package. It allows developers to access specific functionalities with clear dot notation, like robot_beejok.rotation.clockwise.half(), making the code more readable and intuitive.

Dummy Experimentation: Returning A Simple String

To make this guide a more informative learning experience, let's add a dummy experimentation to each function within the modules. In every function defined, we will return a simple string. This will give us a clear indication of which function is being executed, making it easier to follow the code flow and understand package behavior. For example, below is the code contain in clockwise.py, in rotation folder:

#!usr/bin/env python3

"""Module: Contains functions for controlling the rotation portion clockwise."""


def quarter():
    return "The robot is rotating clockwise, completing a quarter turn."

def half():
    return "The robot is rotating clockwise, completing a half turn."


if __name__ == "__main__":
    print("I prefer to be a module, but I can run some test for you.")
    print(quarter())
    print(half())

Creating the Package

To turn this directory structure into a Python package, you need to follow these steps:

Step 1: Initialize the Package

In the root directory (the one containing the robot directory), create an empty file named __init__.py. This file will make the robot directory a Python package.

Step 2: Grouping the Subpackages

Since movement and rotation are subpackages of robot, you should create an empty __init__.py file inside both the movement and rotation directories. This will make them recognized as Python subpackages.

Step 3: Define the Modules

For each module in the subpackages, you can create the respective Python files and define the functions or classes inside them. For example, in slanted/inclined.py, you can define the highspeed() and lowspeed() functions, and similarly, in other modules.

Here's an example of the code in inclined.py might look:

#!usr/bin/env python3

"""Module: Contains functions for controlling the speed when moving on an inclined surface."""


def highspeed():
    return "The robot is moving at a high speed on an inclined surface."


def lowspeed():
    return "The robot is moving at a low speed on an inclined surface."


if __name__ == "__main__":
    print("I prefer to be a module, but I can run some test for you.")
    print(highspeed())
    print(lowspeed())

Step 4: Importing Within the Package

To make functions from one module accessible to another within the package, you can use relative imports. In this example, let's assume you have a main.py file located in the robot_beejok folder, and you want to import highspeed() from declined.py. Here's how you can do it using relative imports:

from movement.slanted.declined import highspeed
print(highspeed())

In this syntax, the leading dot (.) in the import statement indicates a relative import. It tells Python to look for the declined module within the same package as the main.py file (robot_beejok). This way, you can import and use the highspeed() function from declined.py in your main.py script.

Step 5: Importing Outside the Package

In this section, we will explore how to import functions from the robot_beejok package into a script located outside the package. Suppose you have a main.py file outside the robot_beejok package and want to use functions from modules within the package. We will walk you through the steps to achieve this by adding the robot_beejok directory to the Python path.

Python Package directory structure

Let's assume the shown directory structure:

Now, let's say you want to import and use the highspeed() function from the declined.py module within the robot_beejok package.

To do this, follow these steps:

  • Locate your main.py file in the project directory, outside the robot_beejok package.
  • Add the robot_beejok directory to the Python path in main.py by using the following code at the beginning of the script:
import sys
  sys.path.append('..\\robot_beejok')  # Add the robot_beejok directory to the Python path

  • Now you can use a relative import in main.py to import the highspeed() function:
from movement.slanted.declined import highspeed

  • You can now use the highspeed() function as needed in your main.py script:
print(highspeed())

  • By adding the robot_beejok directory to the Python path, you inform Python to look for modules within the robot_beejok package when importing from main.py. This approach allows you to effortlessly import and use functions from within the package without modifying the overall project structure.

Remember that while this method works, using relative imports is generally considered the more preferred way to import modules within the same package, as it keeps your code more organized and maintainable. Nonetheless, modifying the Python path can be helpful in specific scenarios where you need to access modules from outside the package.

Step 6: Building the Package

To build the package, you can use the setuptools library, similar to the previous example. Create a file named setup.py in the root directory with the following content:

from setuptools import setup, find_packages

  setup(
      name="robot_beejok",
      version="0.1",
      packages=find_packages(),
  )

Step 7: Installing the Package

In the terminal, navigate to the root directory (where setup.py is located) and run the following command:

python setup.py sdist

This will create a dist directory containing a compressed archive of your package.

To install your package, use pip (if you use windows):

pip install .\dist\robot_beejok-0.1.tar.gz

To install your package, use pip (if you use Linux):

pip install dist/robot-0.1.tar.gz

Using Your Package

Now that your package is installed, you can import and use it in your Python projects:

from robot_beejok.rotation import clockwise
print(clockwise.half())

OUTPUT:

Conclusion

Creating your first Python package may seem challenging, but it brings significant benefits in terms of code organization and reusability. By following the steps in this comprehensive guide and exploring the dummy experimentation with function names, you have successfully turned your existing directory structure into a Python package. You can now distribute your package, collaborate with others, and leverage its functionalities across various projects.