OpenSite/Guides/Python property expressions

From BathAfrica Documentation
Jump to navigation Jump to search
OpenSite 0.0.1 · DevelopmentSource scope and availability


Store and explicitly recalculate a Python expression on a document property.

Stable identifier
opensite.help.python-property-expressions

Prerequisites

A GUI+Python build or the embedded headless interpreter. The rectangular-section fixture uses the development host. Only evaluate expression sources you trust.

Steps

Distinguish the two languages

Native formulas and Python expressions are separate. Set language="python" for this lesson. See OpenSite/Concepts/Expressions.

Store the expression

The lesson computes a projected length: width × cos(30°). Python uses math.radians to convert degrees before evaluating cosine.

Use Edit → Enable Python Expressions in the desktop, or document.set_python_expressions_enabled in the script. Consent does not itself run the stored expression.

Recalculate explicitly

Use Edit → Recalculate Python Expressions or recalculate_python_expressions(doc). The operation shares the console/editor execution lane.

Review stale and failed results

After changing an input, recalculate again. A retained number marked pending, stale or invalid is not a current result. Opening a file does not silently execute its Python source.

Expected result

For a width of 2 m, the checked result is approximately 1.7320508076 m. The assertion uses a 1e-9 m tolerance.

Limitations

Python expressions are trusted code, not a sandbox. A busy or paused execution lane blocks another evaluation. Stop is cooperative and may wait for native code to return.

Complete example

import math
import opensite

created = opensite.execute("document.create_section", {
    "label": "ProjectionBeam",
    "width": opensite.QuantityArgument(opensite.Q("2 m"), "m"),
    "height": opensite.QuantityArgument(opensite.Q("1 m"), "m"),
})
doc, object_id = created["document"], created["object"]
opensite.execute("document.set_expression", {
    "document": doc, "object": object_id, "property": "height",
    "expression": 'document.get_object("ProjectionBeam").width * math.cos(math.radians(30))',
    "language": "python",
})
# Consent and evaluation are separate operations.
opensite.execute("document.set_python_expressions_enabled", {
    "document": doc, "enabled": True,
})
opensite.recalculate_python_expressions(doc)
height = doc.property(object_id, "height").si_value
assert abs(height - 2.0 * math.cos(math.radians(30))) < 1e-9
print("Projected value:", height, "m")