Making Your Own Unit Conversion Library in Python

Ever wondered how Python libraries are created or thought about building one yourself? Let’s walk through creating a unit conversion class (for tasks like converting miles to kilometers or acres to hectares), testing it, and packaging it into a library. While there are many robust unit conversion libraries available that are more comprehensive than what we’ll create, our main goal here is the process of building and packaging a library. Let’s dive in!

Step 1: Designing the UnitConverter Class

The UnitConverter class will handle length, area, volume, and weight conversions. These will cover the most common metric-to-imperial and imperial-to-metric scenarios, ensuring accuracy with predefined constants.

Here’s the code for converter.py:

class UnitConverter:
    def __init__(self):
        # Length Conversions
        self.meter_to_foot = 3.28084
        self.foot_to_meter = 1 / self.meter_to_foot
        self.meter_to_inch = 39.3701
        self.inch_to_meter = 1 / self.meter_to_inch
        self.kilometer_to_mile = 0.621371
        self.mile_to_kilometer = 1 / self.kilometer_to_mile

        # Area Conversions
        self.acre_to_hectare = 0.404686
        self.hectare_to_acre = 1 / self.acre_to_hectare
        self.square_meter_to_square_foot = 10.7639
        self.square_foot_to_square_meter = 1 / self.square_meter_to_square_foot

        # Volume Conversions
        self.liter_to_gallon = 0.264172
        self.gallon_to_liter = 1 / self.liter_to_gallon
        self.cubic_meter_to_cubic_foot = 35.3147
        self.cubic_foot_to_cubic_meter = 1 / self.cubic_meter_to_cubic_foot

        # Weight Conversions
        self.kilogram_to_pound = 2.20462
        self.pound_to_kilogram = 1 / self.kilogram_to_pound
        self.ton_to_metric_ton = 0.907185
        self.metric_ton_to_ton = 1 / self.ton_to_metric_ton

    # Length Conversions
    def meters_to_feet(self, meters):
        return meters * self.meter_to_foot

    def feet_to_meters(self, feet):
        return feet * self.foot_to_meter

    def meters_to_inches(self, meters):
        return meters * self.meter_to_inch

    def inches_to_meters(self, inches):
        return inches * self.inch_to_meter

    def kilometers_to_miles(self, kilometers):
        return kilometers * self.kilometer_to_mile

    def miles_to_kilometers(self, miles):
        return miles * self.mile_to_kilometer

    # Area Conversions
    def acres_to_hectares(self, acres):
        return acres * self.acre_to_hectare

    def hectares_to_acres(self, hectares):
        return hectares * self.hectare_to_acre

    def square_meters_to_square_feet(self, square_meters):
        return square_meters * self.square_meter_to_square_foot

    def square_feet_to_square_meters(self, square_feet):
        return square_feet * self.square_foot_to_square_meter

    # Volume Conversions
    def liters_to_gallons(self, liters):
        return liters * self.liter_to_gallon

    def gallons_to_liters(self, gallons):
        return gallons * self.gallon_to_liter

    def cubic_meters_to_cubic_feet(self, cubic_meters):
        return cubic_meters * self.cubic_meter_to_cubic_foot

    def cubic_feet_to_cubic_meters(self, cubic_feet):
        return cubic_feet * self.cubic_foot_to_cubic_meter

    # Weight Conversions
    def kilograms_to_pounds(self, kilograms):
        return kilograms * self.kilogram_to_pound

    def pounds_to_kilograms(self, pounds):
        return pounds * self.pound_to_kilogram

    def tons_to_metric_tons(self, tons):
        return tons * self.ton_to_metric_ton

    def metric_tons_to_tons(self, metric_tons):
        return metric_tons * self.metric_ton_to_ton

Step 2: Testing the Class

Here are specific test examples to test the class:

converter = UnitConverter()

# Length Conversions
print(converter.meters_to_feet(1))  # Output: 3.28084
print(converter.kilometers_to_miles(5))  # Output: 3.10686

# Area Conversions
print(converter.acres_to_hectares(1))  # Output: 0.404686
print(converter.square_feet_to_square_meters(100))  # Output: 9.2903

# Volume Conversions
print(converter.liters_to_gallons(10))  # Output: 2.64172
print(converter.cubic_meters_to_cubic_feet(1))  # Output: 35.3147

# Weight Conversions
print(converter.kilograms_to_pounds(70))  # Output: 154.323
print(converter.tons_to_metric_tons(1))  # Output: 0.907185

Step 3: Packaging the Code as a Library (Detailed Explanation)

To make the UnitConverter class reusable across multiple projects we’ll package it into a Python library. This process involves organizing the code into a directory structure, writing configuration files, and making it installable via pip.

1. Create the Directory Structure

Organize your files into a directory structure suitable for a Python package:

unit_converter/
├── unit_converter/
│   ├── __init__.py
│   ├── converter.py
├── setup.py

Explanation:

  • unit_converter/ (Root Directory): The top-level directory, which contains all the files needed for the package.
  • unit_converter/ (Submodule Directory): Contains the actual code for the UnitConverter class.
  • converter.py: This file contains the UnitConverter class definition.
  • __init__.py: A file that marks the submodule as a Python package. This file can be empty or import key components for easier access.
  • setup.py: Configuration for packaging and distribution.

2. Write the setup.py File

The setup.py file defines the metadata and instructions for building and installing the library. Here’s a breakdown of the file:

from setuptools import setup

setup(
    name='unit_converter',               # The name of the library
    version='1.0.0',                     # Version number (follow semantic versioning)
    description='A comprehensive unit conversion library',  # Short description
    author='C. C. Python Programming',                  # Author's name
    author_email='CCPythonProgramming@example.com',  # Contact email
    packages=['unit_converter'],         # List of packages included in the library
    install_requires=[],                 # Dependencies (if any)
    license='MIT',                       # License type
    classifiers=[
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
    ],
    python_requires='>=3.6',             # Minimum Python version requirement
)

Explanation:

  • name: The name of your library, which will be used when installing it via pip install.
  • version: Helps track updates; use semantic versioning (MAJOR.MINOR.PATCH).
  • packages: Lists all Python packages (directories with __init__.py) to include.
  • install_requires: Specifies any dependencies needed for the library. Leave it empty if there are no external requirements.
  • python_requires: Ensures compatibility with certain Python versions.

3. Write the __init__.py File

The __init__.py file in the unit_converter/ directory allows you to specify what gets imported when the package is accessed. In our case, we can simplify access to the UnitConverter class:

from .converter import UnitConverter

This way, when someone imports UnitConverter from the package, they don’t have to specify the converter module explicitly.

4. Install the Library Locally

Once the structure is in place, you can install the package locally for testing. Navigate to the root unit_converter/ directory in your terminal and run:

pip install .

This command:

  1. Locates the setup.py file.
  2. Installs the package into your Python environment.

Output:

Processing c:\py\unit_converter
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: unit_converter
  Building wheel for unit_converter (pyproject.toml) ... done
  Created wheel for unit_converter: filename=unit_converter-1.0.0-py3-none-any.whl size=2261 sha256=960d0ca48ec75714866a1191889201280f9f0c6a9fdcbcf2d9a3de0c15e91a76
  Stored in directory: C:\Users\{user}\AppData\Local\Temp\pip-ephem-wheel-cache-16y28nfs\wheels\ee\70\02\52f55080b88ecca9587638bd4de842e69f05703e4d6ab0c621
Successfully built unit_converter
Installing collected packages: unit_converter
Successfully installed unit_converter-1.0.0

After installation, you can test the package by importing it in any Python script.

NOTE: If you are in a virtual environment when your run pip install . the library will install in that virtual environment /lib folder.

5. Use the Library

Here’s how you would use your library after installation:

from unit_converter import UnitConverter

# Create an instance of the converter
converter = UnitConverter()

# Test some conversions
meters = 10
print(f"{meters} meters is {converter.meters_to_feet(meters)} feet.")

acres = 5
print(f"{acres} acres is {converter.acres_to_hectares(acres):.2f} hectares.")

Your library is just like the libraries you use everyday and can be imported and used as a standalone tool.

6. Prepare for Distribution

To share your library with others, you can upload it to the Python Package Index (PyPI). Follow these steps:

Install Required Tools:

  1. Ensure setuptools and twine are installed:
pip install setuptools twine

Build the Package:

From the root unit_converter/ directory, run:

python setup.py sdist bdist_wheel
  • This creates a dist/ directory containing the distribution files.

Upload to PyPI:

  • Use twine to upload the package:
twine upload dist/*

NOTE: You’ll need a PyPI account to log in during this process.

Install from PyPI:

  • After uploading, the library is publicly available. Anyone can install it with:
pip install unit_converter

Thank you for reading this article. I hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials, please feel free to reach out. Your feedback and suggestions are always welcome!

Happy coding!
C. C. Python Programming

You can also find this article at Medium.com

Leave a Reply