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.
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.
Defining Quantities
Use ct.quantity()
to create values with physical units:
force = ct.quantity("1 N")
area = ct.quantity("1 m^2")
pressure = force / area
You can inspect the result on the right-hand panel. CalcTree automatically handles the unit math.

Other Unit Operations
Create a unit with a magnitude of
1.0
usingct.units()
:kN = ct.units("kN")
Convert to a compatible unit using
.to()
:pressure_kPa = pressure.to("kPa")
Extract the numeric value (without the unit) using
.magnitude()
:value = pressure_kPa.magnitude()
Unit-Aware Validation
CalcTree checks for physical consistency. If you perform an invalid operation (e.g. add time and length), the script will raise an error:
invalid = ct.quantity("5 s") + ct.quantity("2 m") # Raises an error

This acts as built-in quality control when linking Python to other parameter sources.
Working with Page Parameters that include Units
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:
# These are already ct.quantity objects
area = width * height
# Convert area to m²
area_m2 = area.to("m^2")
# Get just the numeric value
value = area_m2.magnitude
There’s no need to manually re-wrap page parameters with ct.quantity()
—they are unit-aware by default when accessed in Python.
Last updated