Skip to main content

UnitPy (Unit Python)



Python PyPI downloads license

UnitPy is a Python package for defining, converting, and working with units.

The goal of the package is to be simple, straightforward, and performant.

This package directly implements NIST (National Institute of Standards and Technology) official unit definitions.


Installation

Pip installable package:

pip install unitpy

pypi: unitpy


Requirements / Dependencies

Python 3.8 and up


Basic Usage

Defining Unit

from unitpy import U, Q, Unit, Quantity
# U = Unit

u = Unit("kilometer")
u = U("kilometer")
u = U("km")
u = U.kilometer
u = U.km

u = U("kilometer/hour")
u = U("km/h")
u = U.kilometer / U.hour
u = U.km / U.h

# properties
print(u.dimensionality)  # [length] / [time]
print(u.dimensionless)   # False
print(u.base_unit)       # meter / second

Defining Quantity

** Quantity = Value + Unit **

from unitpy import U, Q , Unit, Quantity
# Q = Quantity

q = 1 * U("kilometer/hour") 
q = 1 * (U.kilometer / U.hour)
q = Quantity("1 km/h")
q = Q("1 kilometer per hour")
q = Q("1*kilometer/hour")


# properties
print(q.unit)            # kilometer / hour
print(q.dimensionality)  # [length] / [time]
print(q.dimensionless)   # False
print(q.base_unit)       # meter / second

Unit Conversion

from unitpy import U, Q , Unit, Quantity
# Q = Quantity

q = 1 * U("km/h") 
q2 = q.to("mile per hour")
print(q2)  # 0.6213711922 mile / hour

Mathematical operation

from unitpy import U, Q 

q = 1 * U("km/h") 
q2 = 2.2 * U("mile per hour")
print(q2 + q)                 # 2.8213711923 mile / hour
print(q2 - q)                 # 1.5786288077 mile / hour
print(q2 * q)                 # 2.2 kilometer mile / hour**2
print(q2 / q)                 # 2.2 mile / kilometer
print((q2 / q).dimensionless) # True

Other supported functions:

  • sum
  • max
  • min

Temperature

Abbreviations:

  • fahrenheits: degF
  • celsius: degC
  • kelvin: degK, K
  • rankine: degR
from unitpy import U, Q

q = 300 * U("K")
q2 = 200 * U("K")

print(q + q2)        # 500.0 kelvin
print(q.to("degC"))  # 26.85 Celsius
print(q.to("degF"))  # 830.6344444444 Fahrenheit
print(q.to("degR"))  # 166.6666666667 Rankine

Temperature units are non-multiplicative units. They are expressed with respect to a reference point (offset).

degC = 5/9 * (degF - 32)

Default behavior is absolute units.

For relative units use dedicated functions add_rel() or sub_rel().

from unitpy import U, Q

q = 10 * U("degC")
q2 = 5 * U("degC")

# absolute
print(q.to("K"))         # 283.15 kelvin
print(q + q2)            # 288.15 Celsius 
print((q + q2).to("K"))  # 561.3 kelvin
print(q - q2)            # -268.15 Celsius
print((q - q2).to("K"))  # 5.0 kelvin

# relative
print(q.add_rel(q2))      # 15 Celsius
print(q.sub_rel(q2))      # 5 Celsius
print(abs(-10 * U.degC))  # 10 Celsius

Time

from datetime import timedelta
from unitpy import U

a = 1.234 * U.min
print(a)              # 1.234 minute
b = a.to_timedelta()
print(b)              # 0:01:14.040000
print(type(b))        # <class 'datetime.timedelta'>

string formatting

from unitpy import U

a = 1.23432453 * U.min
print(a)                # 1.23432453 minute
print(f"{a:.2f}")       # 1.23 minute
b = 1_000_000 * U.cm
print(b)                # 1000000 centimeter
print(format(b, ","))   # 1,000,000 centimeter
c = 123 * U.inch
print(c)                # 123 inch
print(f"{c:5}")         #   123 inch  (leading spaces)
print(f"{c:05}")        # 00123 inch  (leading zeros)

configuration with .env

To configure the string outputs with environment file (.env):

  1. install python-dotenv. The code uses this to load variables from the .env file
pip install python-dotenv
  1. copy the .env file from this repo into the top level of your repo and edit to your liking

It should now load the environmental variables when you run the code to format it to your liking without any additional code needed.

Numpy Support

Numpy

import numpy as np

from unitpy import Unit, Quantity

# numpy + int
a = np.linspace(0, 4, 5) * Unit.m
b = 1 * Unit.ft
c = a+b
print(a+b)                           # [0.3048 1.3048 2.3048 3.3048 4.3048] meter
print(a-b)                           # [-0.3048  0.6952  1.6952  2.6952  3.6952] meter
a += b
print(a)                             # [0.3048 1.3048 2.3048 3.3048 4.3048] meter

# numpy + numpy
a = np.linspace(0, 4, 5) * Unit.m
b = np.linspace(0, 4, 5) * Unit.ft
print(a+b)                           # [0.     1.3048 2.6096 3.9144 5.2192] meter
print(a-b)                           # [0.     0.6952 1.3904 2.0856 2.7808] meter
a += b
print(a)                             # [0.     1.3048 2.6096 3.9144 5.2192] meter

# numpy * int
a = np.linspace(0, 4, 5) * Unit.m
b = 1.2 * Unit.s
print(a*b)                            # [0.  1.2 2.4 3.6 4.8] meter second
print(a/b)                            # [0.  0.83333333 1.66666667 2.5 3.33333333] meter/second
a *= b
print(a)                              # [0.  1.2 2.4 3.6 4.8] meter second

# numpy * numpy
a = np.linspace(0, 4, 5) * Unit.m
b = np.linspace(0, 4, 5) * Unit.s
print(a*b)                              # [ 0.  1.  4.  9. 16.] meter second
print(a/b)                              # [nan  1.  1.  1.  1.] meter/second
a *= b
print(a)                                # [ 0.  1.  4.  9. 16.] meter second


# numpy functions
a = np.linspace(-2, 4, 5) * Unit.m
print(np.sum(a))                       # 5 meter
print(np.max(a))                       # 4 meter
print(np.abs(a))                       # [2.  0.5 1.  2.5 4. ] meter
print(np.linspace(1*Unit.mm, 2*Unit.ft, 4))  # [  1.         203.86666667 406.73333333 609.6       ] millimeter

Notes

  • this package utilizes the American spellings "meter," "liter," and "ton"
  • supports pickling

Metadata

Release files for unitpy 0.0.19

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unitpy 0.0.19
File Size Uploaded Provenance Actions
unitpy-0.0.19.tar.gz 35.0 kB Without provenance Details for unitpy-0.0.19.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unitpy 0.0.19
File Interpreter ABI Platform Actions
unitpy-0.0.19-py3-none-any.whl Python 3 none any Details for unitpy-0.0.19-py3-none-any.whl

Total release size: 68.5 kB

Release files / unitpy-0.0.19.tar.gz

Download URL unitpy-0.0.19.tar.gz
Size 35.0 kB
Tags Source
SHA-256 checksum
How to use checksums
070241131cc5dd39e294a172c9f441df67e80131a358383073f2e92df44e61d1
BLAKE2b-256 checksum
How to use checksums
cdc9fc6e41545992af31d4f8c6a045ac5df5dab98d5d73e28346ca72dfb07f56
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.10

Release files / unitpy-0.0.19-py3-none-any.whl

Download URL unitpy-0.0.19-py3-none-any.whl
Size 33.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
daa48d0401bdb4c2107e7cd6d72719adeec12a28a8e3f6eb2e9455c6dead949f
BLAKE2b-256 checksum
How to use checksums
911b9aa3ee8bd01cfb78782c603551071fde7621ad80c2c9341314a74272acf9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.10

Security for unitpy 0.0.19

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page