Pint: Safe Unit Conversions in Python

Pint: Safe Unit Conversions in Python

The Problem

Working with physical quantities and unit conversions in Python can be error-prone without explicit unit definitions.

Let’s consider an example where we’re calculating speed from distance and time. Without explicit unit definitions, it’s unclear what units are being used, making it easy for developers to make incorrect assumptions.

distance = 100  # meters? feet? kilometers?
time = 10    # seconds? minutes?

# Manual conversion needed
# assumes distance was in kilometers while in fact it was in meters
speed_kmh = (distance) / (time / 3600)

The Solution

Pint solves this by allowing explicit unit definitions and automatic unit tracking and conversions:

import pint

ureg = pint.UnitRegistry()

# Clear unit definitions
distance = 100 * ureg.meters
time = 10 * ureg.seconds

# Automatic unit conversion
speed = distance / time
speed

Output:

10.0 meter/second
speed.to("kilometers/hour")

Output:

36.0 kilometer/hour

Pint also ensures dimensional consistency in calculations, raising an error if units don’t match.

# Will raise error if units don't match
try:
    wrong_calc = 3 * ureg.meters + 4 * ureg.seconds
except pint.DimensionalityError as e:
    print("DimensionalityError:", e)
DimensionalityError: Cannot convert from 'meter' ([length]) to 'second' ([time])

Link to Pint.

Search

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran