Package for automatically managing units when doing calculations in python.
Project description
UnitsPythonPackage
Python package built with focus on simplicity, ease of use & readability.
Check out SPECIAL_UNITS in python_units/constants.py if you are missing some constants.
If your unit is missing, open a PR with your constant, the appropriate prefix and SI-unit added.
Installation
Install with:
pip install units_python
If you have already installed this package, but want the latest version use:
pip install units_python --upgrade
How to use:
In these examples, we have a physics problem to solve.
We will solve it using python_units to keep track of our units:
Physics Example 1:
How many soccer balls (diameter of 22 cm) can fit inside a 5 x 5 x 2.7 meter room?
Physics Example 2:
A runner has been running 96 km in 8 hours.
- What are their average page?
- If the runner continues at this pace, how far will they go in 46.2 minutes?
Relevant methods:
- .copy(): returns copy of value
my_value = v("9 m**2")
my_copied_value = my_value.copy()
print(my_copied_value) # outputs "9 m**2"
- .round(digits): round value to number of digits (returns nothing)
my_value = v("3.1415926535 m")
my_value.round(4)
print(my_value) # outputs "3.1416 m"
- .sqrt(n=1): takes n-squareroot of value (returns changed value)
my_value = v("9 m**2")
my_value_sqrt = my_value.sqrt(2)
print(my_value_sqrt) # outputs "3 m"
- .value: returns the value of the object (float)
- .unit.get(): returns the unit (string)
- .to(str): input string with desired unit: "km/h", "tons", "hours". Returns string with value and unit
Custom functions:
We supply certain relevant functions:
- sqrt(value, n=1): take n-squareroot of value
import units_python as up
from units_python import v
my_value = v("9 m^2")
my_value_sqrt = up.sqrt(my_value)
print(my_value_sqrt) # outputs "3 m"
- nsqrt(value, n): take n-squareroot of value
other_value = v("21 m^3")
my_value_3sqrt = up.nsqrt(my_value, 3)
print(my_value_sqrt) # outputs "3 m"
- round(value, digits): round value number
third_value = v("3.1415926535 m")
third_value_rounded = up.round(third_value, 4)
print(third_value_rounded) # outputs "3.1416 m"
What units can I use?
You can find all avaliable units in python_units.constant.UNITS & python_units.constant.SPECIAL_UNITS.
You can find all avaliable prefixes in python_units.constant.PREFIXES.
You can combine prefixes and units in whatever way you like. You can also combine multiple units: 'ton/liter', 'kg*liter/hour' etc.
What you, at this time, cannot do:
- exp
- value ** value (value ** constant works!)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.