Working with Units in Python
CalcTree supports unit-aware calculations in Python, allowing you to safely perform operations on physical quantities with automatic unit handling and validation.
Last updated
CalcTree supports unit-aware calculations in Python, allowing you to safely perform operations on physical quantities with automatic unit handling and validation.
Last updated
Create physically meaningful calculations by attaching units to values in your Python scripts using ct.quantity()
. This makes unit consistency a built-in feature of your calculations, reducing the risk of error when working with inputs or outputs across multiple sources.
Use ct.quantity()
to create values with physical units:
You can inspect the result on the right-hand panel. CalcTree automatically handles the unit math.
Create a unit with a magnitude of 1.0
using ct.units()
:
Convert to a compatible unit using .to()
:
Extract the numeric value (without the unit) using .magnitude()
:
CalcTree checks for physical consistency. If you perform an invalid operation (e.g. add time and length), the script will raise an error:
This acts as built-in quality control when linking Python to other parameter sources.
When you reference parameters from other sources (e.g. MathJS, tables, spreadsheets), they may already include physical units. These are passed into Python as ct.quantity()
objects.
You can use them directly in calculations, convert them, or extract numeric values as needed.
Example:
Assume your page has two parameters:
width = 100 mm
(from MathJS)
height = 2.5 m
(from a spreadsheet)
In Python:
There’s no need to manually re-wrap page parameters with ct.quantity()
—they are unit-aware by default when accessed in Python.
CalcTree uses the Python library pint
to enable handling units. You can access pint's documentation .