Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Pint: Safe Unit Conversions in Python

Table of Contents

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran