Overview#
Parameters are the beating heart of parametric Fusion models, and the API treats them as first-class objects. Through the API you can inspect every dimension a design owns, create named user parameters that drive geometry, change values and watch the model regenerate, and export or import parameters as tables. This is the foundation for configurators, part families, and design-checking tools.
If you have used the Change Parameters dialog (open it from Modify > Change Parameters), the API mirrors it almost one to one.
Where to find it#
In the interface: Solid > Modify > Change Parameters shows two groups, User Parameters and Model Parameters (plus favorites and linked parameters in recent versions). In the API reference, search for Design.userParameters, Design.allParameters, Component.modelParameters, Parameter, UserParameter, ModelParameter, ParameterList, UserParameters, and ValueInput.
The parameter classes#
| Class | Meaning | Where to get it |
|---|---|---|
Parameter | Base: name, expression, unit, value, comment | Any list below |
UserParameter | Created by you; no owning feature | design.userParameters |
ModelParameter | Created by a sketch dimension or feature | component.modelParameters |
ParameterList | Flat list of parameters | design.allParameters |
UserParameters | Collection with add and itemByName | design.userParameters |
Important properties of Parameter:
name: the identifier used in expressions. Model parameters get automatic names liked1,d2, which you can rename.expression: the text formula, such as'width * 2 + 5 mm'.value: the computed numeric result in internal units (cm, radians, or unitless).unit: the unit string such as'mm','deg', or''for unitless.comment: free text.isFavorite: whether the parameter is pinned in the dialog.valueType:NumericParameterValueTypeorTextParameterValueType.valueis only valid for numeric parameters; text parameters usetextValue.isDeletable,dependencyParameters(parameters this one depends on) anddependentParameters(parameters that depend on it).- On
ModelParameteronly:role(what the parameter is used for, such as "Depth" for an extrude) andcreatedBy(the feature, sketch dimension or construction plane that created it).
Step by step#
1. List all parameters#
import adsk.core, adsk.fusion, traceback
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
design = adsk.fusion.Design.cast(app.activeProduct)
lines = []
for p in design.allParameters:
kind = 'user' if adsk.fusion.UserParameter.cast(p) else 'model'
if p.valueType == adsk.fusion.ParameterValueTypes.TextParameterValueType:
val = p.textValue # value only works for numeric parameters
else:
val = f'{p.value:.4f}'
lines.append(f'{p.name:12s} {p.expression:18s} = {val} [{p.unit}] ({kind})')
ui.messageBox('\n'.join(lines) or 'No parameters', 'Parameters')
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
value is in internal units, so a 10 mm parameter reports 1.0. The expression shows exactly what the user typed. When you want a number in the document's display unit, divide by the conversion or use design.unitsManager.convert(p.value, 'cm', 'mm'). UnitsManager.convert(value, fromUnits, toUnits) converts between compatible units, and evaluateExpression(expression, units) "gets the value (in internal units) of the expression", so treat its result as database units (cm) and convert afterwards. UnitsManager.isValidExpression validates a user string first.
2. Create a user parameter#
design = adsk.fusion.Design.cast(app.activeProduct)
params = design.userParameters
width = params.add(
'width', # name
adsk.core.ValueInput.createByString('40 mm'), # initial value
'mm', # unit type
'Overall width') # comment
The signature is UserParameters.add(name, value, units, comment). Autodesk's Parameters dialog topic says names can contain letters and numbers plus these symbols: underscore, double quote, dollar sign, degree sign and micro sign; the reference says a name must be unique among all parameters in the design. > Note: not confirmed in Autodesk's documentation: other naming rules (such as a leading digit, or clashes with unit names like in or mm). Treat adding an existing name as an error and check first:
existing = params.itemByName('width')
if existing is None:
existing = params.add('width', adsk.core.ValueInput.createByString('40 mm'), 'mm', '')
For a unitless count use '' as the unit and createByReal(4):
params.add('n_holes', adsk.core.ValueInput.createByReal(4), '', 'Number of holes')
3. Edit a parameter#
p = design.userParameters.itemByName('width')
p.expression = '55 mm' # triggers regeneration of dependent features
Assigning expression is almost always the right choice; it is the equivalent of the Expression column in the Parameters dialog, and a bare number is read in the document's units. Setting p.value = 5.5 is also possible and assigns in database units (the reference says it sets or resets the expression), so it replaces any formula with a plain number. If a feature cannot regenerate after an edit, Fusion flags it in the timeline. Your script can detect that by checking feature.healthState on suspect features (adsk.fusion.FeatureHealthStates: HealthyFeatureHealthState, WarningFeatureHealthState, ErrorFeatureHealthState, SuppressedFeatureHealthState, RolledBackFeatureHealthState, UnknownFeatureHealthState). Design.modifyParameters changes many parameters at once and is documented as more efficient than one at a time.
Dependent parameters follow automatically. If depth has the expression width / 2, changing width changes depth. p.dependencyParameters lists the parameters p depends on, and p.dependentParameters those that depend on p.
4. Drive geometry through parameters#
Anywhere the API accepts a ValueInput, a parameter name inside a string expression creates a live link:
ext_in.setDistanceExtent(False, adsk.core.ValueInput.createByString('width / 2'))
You can also assign an expression directly to a model parameter:
dim.parameter.expression = 'width'
and use Parameter.expression formulas. Autodesk's Parameters reference lists the functions cos, sin, tan, acos, asin, atan, the hyperbolic variants, sqrt, sign, exp, ln, log, abs, floor, ceil, round, max(expr1; expr2), min(expr1; expr2), pow(expr1; expr2), random() and if(condition; then; else) with and/or. Note the semicolon argument separator in that reference. > Note: not confirmed in Autodesk's documentation: whether a comma separator is accepted when you set expression from the API (the topic's examples use semicolons). Text parameters may use expressions such as text1 + text2.
5. Delete a parameter#
p = design.userParameters.itemByName('old_param')
if p and p.deleteMe():
pass
UserParameter.deleteMe() deletes the parameter, which "can only be deleted if it is a UserParameter and it is not referenced by other parameters". Remove dependencies first; check isDeletable. Model parameters "cannot be deleted because features depend on them" (the rare exception is a model parameter with no dependents, where isDeletable is true); otherwise delete the feature or sketch dimension that owns them.
6. Rename a parameter#
Setting p.name = 'new_name' renames it; the reference says this "can fail if the name is not unique with respect to all other parameters in the design". > Note: not confirmed in Autodesk's documentation: that references in other expressions are updated automatically; check the dependants after renaming.
A table-driven part family#
A classic use is generating several variants from a table. The following script reads a CSV beside the document with columns name,width,depth,height and, for each row, sets the parameters, exports an STEP file, and restores the original values.
import adsk.core, adsk.fusion, traceback, csv, os
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
design = adsk.fusion.Design.cast(app.activeProduct)
dlg = ui.createFileDialog()
dlg.title = 'Select variants CSV'
dlg.filter = 'CSV files (*.csv)'
if dlg.showOpen() != adsk.core.DialogResults.DialogOK:
return
csv_path = dlg.filename
out_dir = os.path.dirname(csv_path)
params = design.userParameters
# remember originals
names = ('width', 'depth', 'height')
original = {n: params.itemByName(n).expression for n in names}
exported = 0
with open(csv_path, newline='') as fh:
for row in csv.DictReader(fh):
for n in names:
params.itemByName(n).expression = f'{row[n]} mm'
adsk.doEvents() # let Fusion regenerate and repaint
step_path = os.path.join(out_dir, row['name'] + '.step')
opts = design.exportManager.createSTEPExportOptions(step_path)
design.exportManager.execute(opts)
exported += 1
for n, expr in original.items():
params.itemByName(n).expression = expr
ui.messageBox(f'Exported {exported} variants to\n{out_dir}')
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Prerequisites: the open design must already contain user parameters named width, depth and height that drive the geometry. The script restores the original expressions afterwards so the user's document is left unchanged apart from timeline recomputes. Autodesk ships a related sample, "Set parameters from a CSV file and export to STEP", which is worth comparing. File dialogs: FileDialog.showOpen() and showSave() return a DialogResults value, and the chosen path is in filename; the filter string takes the form shown above.
Linked and favorite parameters#
p.isFavorite = True includes a parameter in the Favorites list of the Parameters dialog (Autodesk's dialog topic also says a parameter created on the fly is automatically added to favorites). > Note: not confirmed in Autodesk's documentation: linking parameters between designs through the API.
Options reference#
| Member | What it does | Notes |
|---|---|---|
design.userParameters.add(name, valueInput, unit, comment) | Create user parameter | Raises on duplicate or bad name |
userParameters.itemByName(name) | Lookup | Returns None if missing |
design.allParameters | User plus all model parameters | Flat, read-only list |
component.modelParameters | Parameters of one component | Names auto-assigned |
parameter.expression | Formula string | Assign to edit |
parameter.value | Result in internal units | Assigning replaces formula |
parameter.unit | Unit string, empty for unitless | Documented as a getter only |
parameter.comment | Description | Free text |
parameter.isFavorite | Pin in dialog | Boolean |
userParameter.deleteMe() | Remove user parameter | Only if not referenced; see isDeletable |
unitsManager.evaluateExpression(expr, unit) | Evaluate an expression | Result in internal units |
unitsManager.convert(v, from, to) | Convert value | Internal units are cm and radians |
Tips and pitfalls#
Tip: Group changes with
Design.modifyParameterswhere you can, and avoid callingadsk.doEvents()after every assignment; Autodesk notes that letting Fusion draw after each change costs time (it is useful only when you want to watch progress). Long timelines recompute on edits.
Tip: Name parameters with a prefix for your tool (
gt_width) to avoid collisions with the user's own names.
Warning:
ValueInput.createByReal(10)for a length is 10 cm, not 10 mm. This is the single most common bug in parameter scripts. Use strings with units.
Warning: Parameter edits happen inside the user's document. If a regeneration fails the feature shows an error; write defensive code that reverts the expression in an
exceptblock.
Warning: Not confirmed in Autodesk's documentation: whether parameter names are case-sensitive. Use one consistent case.
Practice exercise#
Create a script that ensures three user parameters exist (box_w, box_d, box_h) with defaults of 40, 30 and 20 mm, then builds a box from them as in the previous page. Add a second script that prompts with ui.inputBox('Width in mm', 'Box width', '40'), writes the value to box_w, and verifies that the box updates. Expected result: running the second script resizes the box without recreating it. The inputBox call returns a tuple of (value, cancelled).
Reading parameters from sketches and features#
Every dimension you place in a sketch, and every numeric field in a feature dialog, produces a model parameter. You can reach it from the object that owns it. A sketch dimension exposes dim.parameter. An extrude feature exposes its distance through ext.extentOne (an ExtentDefinition) and, for distance extents, extentOne.distance, which is a ModelParameter (Autodesk's extrude sample casts it with adsk.fusion.ModelParameter.cast(disDef.distance) and sets .value). This lets you read or edit a single feature without searching by name:
ext = root.features.extrudeFeatures.item(0)
dist_param = ext.extentOne.distance # ModelParameter for distance extents
app.log(f'{dist_param.name}: {dist_param.expression}')
dist_param.expression = 'width / 2'
Cast ext.extentOne to adsk.fusion.DistanceExtentDefinition before reading .distance if the extent type could vary; cast returns None for other types.
Naming model parameters is good practice when a tool needs to find them later. Set dist_param.name = 'boss_height'; thereafter the parameter is visible to expressions and to itemByName lookups through design.allParameters.itemByName('boss_height').
Exporting and importing parameter sets#
A configurator often needs to save a snapshot of parameter values and restore it later. Because expression is plain text, a dictionary works well:
import json
def snapshot(design):
return {p.name: p.expression for p in design.userParameters}
def restore(design, snap):
for name, expr in snap.items():
p = design.userParameters.itemByName(name)
if p:
p.expression = expr
with open('preset_a.json', 'w') as fh:
json.dump(snapshot(design), fh, indent=2)
Restoring only user parameters keeps the logic simple, since model parameters are normally derived from them. The same technique underlies the Fusion Configurations feature at a higher level; if you only need switchable variants without code, use Configurations instead (see the parametric design section).
Related#
- Creating sketches and features
- Object model
- Parametric design section of this guide
- Event handlers (reacting to parameter changes)