Skip to content

fontlab.flExpression

flExpression

Formula string for axis-driven values.

What is flExpression?

An flExpression stores and evaluates a text formula that can reference design-space axis values and font metric names. For example:

"ascender * 0.7"
"xHeight + stemWidth"
"weight < 400 ? 50 : 100"

When FontLab evaluates an expression, it substitutes the current values of axis tags (like wght, wdth) and metric names (like ascender, xHeight, capHeight) for the variable names in the formula, then computes the result.

Expressions are used by guidelines, anchors, and parametric shape nodes to make their positions vary smoothly across the design space.

Tutorial

from PythonQt.QtCore import QPointF
import fontlab as fl
from fontlab import flExpression

# ============================================================
# 1. Create an expression and inspect it.
#    This is standalone — not yet attached to any object.
# ============================================================

expr = flExpression()
expr.expression = "ascender * 0.7"

print("Has expression:", expr.hasExpression())  # True
print("Has error:", expr.hasError())             # False (not yet evaluated)
print("Is ready:", expr.ready)                   # False (not yet evaluated)

# ============================================================
# 2. Inspect which variables the formula depends on.
# ============================================================

deps = expr.variables({})   # {} = no alias substitution
print("Depends on:", deps)  # ['ascender']

# ============================================================
# 3. Rename variables for human-friendly display.
#    Useful if you are showing the expression in a UI panel.
# ============================================================

alias_map = {"ascender": "Ascender Height"}
friendly = expr.expression(alias_map)
print("Friendly formula:", friendly)  # "Ascender Height * 0.7"

# ============================================================
# 4. Read an expression from an existing guideline.
#    Guidelines can be formula-driven — for example, the
#    x-height guideline might use "xHeight" as its expression.
# ============================================================

font = fl.CurrentFont()
for gl in font.guidelines:
    # flGuideLine exposes its expression through the y-property:
    e = gl.expressionY  # returns flExpression
    if e and e.hasExpression():
        print(f"Guideline at y={gl.centerPoint.y():.0f}: "
              f"formula = '{e.expression}'")
        if e.hasError():
            from fontlab import flPropertiesProcessor
            err_msg = flPropertiesProcessor.errorToStr(e.error)
            print(f"  ERROR: {err_msg}")

# ============================================================
# 5. Assign an expression to a guideline.
#    Make a horizontal guideline track the x-height
#    so it always sits at the right height in every master.
# ============================================================

from fontlab import flGuideLine

# Create a new guideline at y=500 initially:
gl = flGuideLine(0.0, QPointF(0, 500))
font.appendGuideline(gl)

# Now attach an expression so it tracks xHeight automatically:
gl.expressionY.expression = "xHeight"
gl.expressionY.resetReady()   # force re-evaluation

fl.Update()
print("Guideline is now tracking xHeight.")

Common Scripting Patterns

Validate a formula before assigning it

import fontlab as fl
from fontlab import flExpression

font = fl.CurrentFont()
# Test expressions before applying:
for formula in ["=xHeight", "=capHeight * 0.5", "=badVariable + 100"]:
    expr = flExpression()
    expr.expression = formula
    valid = expr.validate(font)   # check against font's variable scope
    print(f"'{formula}': valid={valid}")

Copy a formula from one guideline to another

import fontlab as fl

font = fl.CurrentFont()
guides = font.guidelines

if len(guides) >= 2:
    src_formula = guides[0].expression or ""
    if src_formula:
        guides[1].expression = src_formula
        fl.Update()
        print(f"Copied formula '{src_formula}' to '{guides[1].name}'")

Inherited binding members: flObject.

Constructors: flExpression() flExpression(flObject) flExpression(flExpression) flExpression(string)

Native bases: object

Captured native MRO: flExpression, object

Native new allocation evidence (not an init overload): (args, *kwargs) Create and return a new object. See help(type) for accurate signature.

Supplemental documentation: Expression holder. The captured declaration exposes expression, hasExpression, hasError, error, clearError, isNeedToComplete, resetReady, ready and variables. It is created with no captured constructor overloads. It also carries the shared object members changed, clone, cloneObject, getProperty, setProperty, release, remove and update and the shared attributes id, name, type, isValid and isNull.

Source: FontLab Proteus API documentation

Source: generated/fontlab.py: flExpression captured declaration

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
__init__ function (self, /, *args: Any, **kwargs: Any) -> None Initialize self. (shared captured text)
changed function (self) -> Any (shared captured text)
checkInitHistoryState function (self, history_ix: int) -> Any (shared captured text)
clearAboveHistory function (self, history_ix: int) -> Any (shared captured text)
clearError function (self) -> Any Clears any cached error state.
clearFlag function (self, f: int) -> Any (shared captured text)
clearFlags function (self) -> Any (shared captured text)
clone function (self, *args: Any, **kwargs: Any) -> Any Clone the object (shared captured text)
cloneObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
createObject function (*args: Any, **kwargs: Any) -> Any FlObject/Nothing createObject(int); (shared captured text)
currentHistoryState function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
error attribute Any The error code from the last evaluation.
expression function (self, aliases: dict[str, str]) -> str Returns the formula string with variables substituted according to aliases.
flObjectFlags attribute dict (shared captured text)
flag function (self, f: int) -> Any (shared captured text)
getProperties function (self, *args: Any, **kwargs: Any) -> Any Get object's properties list (shared captured text)
getProperty function (self, *args: Any, **kwargs: Any) -> Any Get object property by 'key' or number (shared captured text)
getPropertyFloat function (self, *args: Any, **kwargs: Any) -> Any Get float object property by 'key' (shared captured text)
getPropertyInt function (self, *args: Any, **kwargs: Any) -> Any Get int object property by 'key' (shared captured text)
hasChanges attribute Any (shared captured text)
hasError function (self) -> bool Returns True if the last evaluation attempt produced an error.
hasExpression function (self) -> bool Returns True if the expression string is non-empty.
hasHistoryState function (self, history_ix: int) -> Any (shared captured text)
hasHistoryStates attribute Any (shared captured text)
haveObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
historyStates function (self, accepted_state: bool) -> Any (shared captured text)
id attribute Any Object id (shared captured text)
independedAll function (self) -> Any (shared captured text)
initialHistoryState function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
instanceType function (*args: Any, **kwargs: Any) -> Any (shared captured text)
isChanged attribute Any (shared captured text)
isEqual function (self, arg0: flObject) -> Any (shared captured text)
isNeedToComplete function (self) -> bool Returns True if the expression cannot yet be evaluated because it references variables that have not been defined (e.g. an axis tag that hasn't been created yet).
isNull attribute Any (shared captured text)
isPresent attribute Any (shared captured text)
isReleased attribute Any (shared captured text)
isValid attribute Any (shared captured text)
name attribute Any Object name (shared captured text)
propertyNames function (self, *args: Any, **kwargs: Any) -> Any PropertyNames(): sorted snapshot of dynamic property keys (shared captured text)
ready attribute Any Whether the expression has been evaluated and is current.
refCnt attribute Any Object references count (shared captured text)
release function (self) -> Any (shared captured text)
remove function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
removeChild function (self, arg0: flObject) -> Any (shared captured text)
resetReady function (self) -> Any Marks the expression as needing re-evaluation.
restoreHistoryState function (self, history_ix: int) -> Any (shared captured text)
setFlag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
setProperty function (self, *args: Any, **kwargs: Any) -> Any Set object property by 'key' or number (shared captured text)
setPropertyFloat function (self, *args: Any, **kwargs: Any) -> Any Set float object property by 'key' (shared captured text)
setPropertyInt function (self, *args: Any, **kwargs: Any) -> Any Set int object property by 'key' (shared captured text)
tag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
type attribute Any Object type (shared captured text)
update function (self) -> Any (shared captured text)
variables function (self, *args: Any, **kwargs: Any) -> Any Returns a list of the variable names referenced in the formula.