
Cadquery
- 2 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Reference the CadQuery Python parametric CAD library for Workplane, Sketch, and Assembly APIs plus STEP/DXF/STL/glTF import and export.
About
A structured reference for CadQuery, a Python parametric 3D CAD scripting library built on OpenCascade, covering Workplane, Sketch, Assemblies with constraint solving, selectors, and multi-format I/O. A developer loads it when scripting CAD models in Python.
- Workplane API: extrude, revolve, sweep, loft, fillet, chamfer, shell
- Assembly constraint solver and STEP/DXF/STL/glTF export
Cadquery by the numbers
- 2 all-time installs (skills.sh)
- Ranked #1,291 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill cadqueryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Reference the CadQuery Python parametric CAD library for Workplane, Sketch, and Assembly APIs plus STEP/DXF/STL/glTF import and export.
Files
CadQuery リファレンス
CadQuery — OpenCascade ベースの Python 製パラメトリック 3D CAD モデリングライブラリ。 スクリプトとして CAD モデルを記述でき、Workplane / Sketch / Assembly といった抽象レイヤー上で 制約ベースの設計を可能にする。STEP / DXF / STL / glTF など多様な業界標準フォーマットの入出力に対応。 公式ドキュメント (cadquery.readthedocs.io) の全 20 ページを 14 カテゴリに構造化。
ディレクトリ構造
.claude/skills/cadquery/
├── SKILL.md ← このファイル(エントリーポイント)
└── references/
├── getting-started/README.md ← 入門索引(5 ページ)
├── workplane/README.md ← Workplane page 索引(9 ページ)
├── sketch/README.md ← Sketch page 索引(2 ページ)
├── assemblies/README.md ← Assemblies page 索引(4 ページ)
├── free-function/README.md ← Free Function API 索引(9 ページ)
├── visualization/README.md ← Visualization 索引(5 ページ)
├── file-io/README.md ← File I/O 索引(15 ページ)
├── examples/README.md ← Examples 索引(9 ページ / 33 例カバー)
├── api/README.md ← API Reference + Cheatsheet 索引(14 ページ)
├── selectors/README.md ← Selectors Reference 索引(8 ページ)
├── classes/README.md ← Class Summary 索引(4 ページ)
├── cqgi/README.md ← CQGI 索引(7 ページ)
├── extending/README.md ← Plugin/拡張ガイド索引(10 ページ)
└── misc/README.md ← Citing 索引(1 ページ)探索手順
1. ユーザーのタスクに最も関連するカテゴリを特定する 2. そのカテゴリの README.md を読む 3. README.md 内の一覧から必要な個別ファイルを選んで読む 4. 必要に応じて関連ページのリンクを辿る
カテゴリ → README.md マッピング
| タスク例 | カテゴリ | README パス |
|---|---|---|
| インストール、最初の一歩、設計原則、BREP/Workplane/Selectors の概念理解 | getting-started | references/getting-started/README.md |
| 2D ワイヤ作成(lineTo, polyline, threePointArc 等)、3D 押し出し(extrude, revolve, sweep, loft)、ブール演算(cut, union)、フィレット・シェル、Workplane chain と Stack | workplane | references/workplane/README.md |
| 制約付きスケッチ(segment, arc, spline, constrain, solve)、フェース構築(rect, circle, polygon, slot)、Workplane との統合 | sketch | references/sketch/README.md |
| 部品組立、Assembly tutorial、Object locations、9 種制約(Point/Axis/Plane/PointInPlane/Fixed 等)、Assembly colors | assemblies | references/assemblies/README.md |
| Workplane を使わない関数型 API(box/sphere/cylinder, fuse/cut, fillet/chamfer/shell, extrude/revolve/sweep/loft, text 等) | free-function | references/free-function/README.md |
| 可視化(show 関数、VTK 統合、スクリーンショット、Control points、Styling、Jupyter インライン表示) | visualization | references/visualization/README.md |
| ファイル入出力(STEP/DXF/STL/glTF/SVG/AMF/3MF/TJS/VRML)、Assembly export, CQ-editor の show_object 規約 | file-io | references/file-io/README.md |
| 33 個のモデリング例(Plate, Mirroring, Workplanes, Lofts, Holes, Bottle, Lego, Bearing, Enclosure, Braille, Cycloidal Gear 等) | examples | references/examples/README.md |
| API 一覧(Sketch / Workplane 2D/3D / File / Iteration / Stack / Selectors / Assemblies のメソッドシグネチャ)、API Cheatsheet | api | references/api/README.md |
| Selector 文字列構文("%face", ">Z", "<<Y", "+Z", " | X", "#X" 等)、組合せ演算子、Nth 系、Topological(ancestors/siblings) | selectors |
| クラス階層(Shape, Vertex, Edge, Wire, Face, Shell, Solid, Compound, CompSolid, Mixin1D/3D, Vector, Matrix, Plane, Location, BoundBox, Color, Material, Selector 階層) | classes | references/classes/README.md |
| スクリプト実行環境、パラメータ駆動モデリング、show_object/debug、BuildResult、CQModel | cqgi | references/cqgi/README.md |
| Plugin 開発、CadQuery 拡張、OpenCascade 直接呼び出し、Stack 操作、newObject/findSolid、map/apply/invoke | extending | references/extending/README.md |
| 引用情報(学術用途、Zenodo DOI) | misc | references/misc/README.md |
Assemblies
Classes and methods for combining Workplane and Shape objects into hierarchical, constraint-solved assemblies.
Method Summary
| Method / Class | Signature | Description |
|---|---|---|
Assembly | Assembly(obj=None, loc=None, name=None, color=None, material=None, metadata=None) | Create a nested assembly of Workplane/Shape objects |
Assembly.add | add(obj, loc=None, name=None, color=None, material=None, metadata=None) | Add a sub-assembly or shape to the assembly |
Assembly.save | save(path, exportType=None, mode="default", tolerance=0.1, angularTolerance=0.1, **kwargs) | Save the assembly to a file |
Assembly.constrain | constrain(q1, q2, kind, param=None) | Define a constraint between two assembly parts |
Assembly.solve | solve(verbosity=0) | Solve all constraints and update component positions |
Constraint | Constraint(subshapes, sublocs, kind, param=None) | Low-level constraint specification object |
Color | Color(r=None, g=None, b=None, a=1.0) | RGBA color wrapper for assembly components |
Signature / Usage
import cadquery as cq
# Build an assembly
assy = (
cq.Assembly()
.add(cq.Workplane("XY").box(1, 1, 1), name="base", color=cq.Color("red"))
.add(cq.Workplane("XY").sphere(0.5), name="ball",
loc=cq.Location((0, 0, 1)))
)
# Constraint-based assembly
assy = (
cq.Assembly()
.add(cq.Workplane("XY").box(2, 2, 1), name="bottom")
.add(cq.Workplane("XY").box(1, 1, 1), name="top")
.constrain("bottom@faces@>Z", "top@faces@<Z", "Plane")
.solve()
)
assy.save("assembly.step")Options / Props
Assembly(obj, loc, name, color, material, metadata)
| Name | Type | Description |
|---|---|---|
obj | `Shape \ | Workplane \ |
loc | `Location \ | None` |
name | `str \ | None` |
color | `Color \ | None` |
material | `str \ | None` |
metadata | `dict \ | None` |
Assembly.add(obj, loc, name, color, material, metadata)
| Name | Type | Description |
|---|---|---|
obj | `Shape \ | Workplane \ |
loc | `Location \ | None` |
name | `str \ | None` |
color | `Color \ | None` |
Assembly.save(path, exportType, mode, tolerance, angularTolerance)
| Name | Type | Description |
|---|---|---|
path | str | Output file path |
exportType | `str \ | None` |
mode | str | "default" (overwrite), "append" |
tolerance | float | Linear tessellation tolerance |
angularTolerance | float | Angular tessellation tolerance |
Assembly.constrain(q1, q2, kind, param)
| Name | Type | Description |
|---|---|---|
q1 | str | Query string for first component (e.g. "part1@faces@>Z") |
q2 | str | Query string for second component |
kind | str | Constraint type (see table below) |
param | `float \ | None` |
Assembly.solve(verbosity)
| Name | Type | Description |
|---|---|---|
verbosity | int | 0 = silent, 1 = print solver output |
Constraint Types
| Kind | Description |
|---|---|
"Plane" | Align two faces coplanar (normal + position) |
"Point" | Coincide two points |
"Axis" | Align two axes (directions) |
"PointInPlane" | Constrain a point to lie on a plane |
"PointOnLine" | Constrain a point to lie on a line |
"Fixed" | Fix a component at its current location |
"FixedPoint" | Fix a point at a specific location |
"FixedRotation" | Fix the rotation of a component |
"FixedAxis" | Fix an axis direction |
Constraint Query String Syntax
Format: "<name>@<type>@<selector>"
<name>: Assembly component name (or""for root)<type>:faces,edges,vertices<selector>: Any valid selector string (e.g.>Z,<X,\|Y)
Example: "pin@faces@>Z" — the topmost face of the component named "pin"
Color Usage
# Named colors
cq.Color("red")
cq.Color("green")
cq.Color("blue")
# RGBA
cq.Color(0.8, 0.2, 0.1, 1.0)Notes
Assembly.solve()must be called after all constraints are defined to compute final positions.- Component names must be unique within an assembly.
- The constraint system uses a 6-DOF solver; under-constrained assemblies will have remaining degrees of freedom.
Locationobjects can be created withcq.Location(cq.Vector(x, y, z))orcq.Location((x, y, z)).- STEP export preserves assembly hierarchy; STL/GLTF flatten geometry.
Related
- File Management and Export
- Stack and Selector Methods
- Selectors
CadQuery Cheatsheet
Quick-reference for CadQuery's most commonly used operations, selectors, and patterns.
3D Construction
Primitives
| Method | Signature | Description |
|---|---|---|
box | box(length, width, height) | Create a rectangular solid |
sphere | sphere(radius) | Create a spherical shape |
cylinder | cylinder(height, radius) | Create a cylindrical shape |
wedge | wedge(dx, dy, dz, xmin, zmin, xmax, zmax) | Create a wedge/frustum |
text | text(txt, fontsize, distance) | Generate 3D extruded text |
Additive Operations
| Method | Signature | Description |
|---|---|---|
extrude | extrude(until) | Extend a 2D profile into 3D |
revolve | revolve(angleDegrees) | Rotate a profile around an axis |
loft | loft(ruled=False) | Create a surface between profiles |
sweep | sweep(path, isFrenet, transitionMode) | Move a profile along a path |
twistExtrude | twistExtrude(distance, angleDegrees) | Extrude while twisting |
Subtractive Operations
| Method | Signature | Description |
|---|---|---|
cutBlind | cutBlind(until) | Remove material to a specified depth |
cutThruAll | cutThruAll() | Cut completely through the object |
hole | hole(diameter, depth) | Create a cylindrical hole |
cboreHole | cboreHole(diameter, cboreDiameter, cboreDepth) | Counterbored hole |
cskHole | cskHole(diameter, cskDiameter, cskAngle) | Countersunk hole |
shell | shell(thickness) | Hollow out a solid |
Boolean Operations
| Method | Signature | Description |
|---|---|---|
union | union(toUnion=None) | Combine shapes |
cut | cut(toCut) | Remove one shape from another |
intersect | intersect(toIntersect) | Keep only overlapping portions |
combine | combine(clean=True) | Combine all stack items |
Use combine parameter shorthand on creation methods:
combine="a"— add (union)combine="s"— subtractcombine="i"— intersect
Edge Modifications
| Method | Signature | Description |
|---|---|---|
fillet | fillet(radius) | Round selected edges |
chamfer | chamfer(length, length2=None) | Bevel selected edges |
2D Construction
Shapes
| Method | Signature | Description |
|---|---|---|
rect | rect(xLen, yLen, centered=True) | Rectangle |
circle | circle(radius) | Circle |
ellipse | ellipse(x_radius, y_radius) | Ellipse |
slot2D | slot2D(length, diameter, angle=0) | Rounded slot |
polyline | polyline(listOfXYTuple) | Connected line segments |
Positioning
| Method | Signature | Description |
|---|---|---|
center | center(x, y) | Shift the local coordinate origin |
moveTo | moveTo(x, y) | Move current point to absolute position |
move | move(xDist, yDist) | Move current point by relative distance |
Lines and Arcs
| Method | Signature | Description |
|---|---|---|
lineTo | lineTo(x, y) | Line to absolute coordinates |
line | line(xDist, yDist) | Relative line |
vLine | vLine(distance) | Vertical line |
hLine | hLine(distance) | Horizontal line |
polarLine | polarLine(distance, angle) | Line by distance and angle |
threePointArc | threePointArc(point1, point2) | Arc through midpoint to endpoint |
sagittaArc | sagittaArc(endPoint, sag) | Arc by sagitta value |
radiusArc | radiusArc(endPoint, radius) | Arc by radius |
spline | spline(listOfXYTuple) | Spline through points |
close | close() | Close the current wire |
Arrays
| Method | Signature | Description |
|---|---|---|
rarray | rarray(xSpacing, ySpacing, xCount, yCount) | Rectangular array of points |
polarArray | polarArray(radius, startAngle, angle, count) | Polar array of points |
Sketch API
Basic Shapes
| Method | Signature | Description |
|---|---|---|
rect | rect(w, h, angle=0, mode="a") | Rectangle |
circle | circle(r, mode="a") | Circle |
ellipse | ellipse(a1, a2, angle=0, mode="a") | Ellipse |
trapezoid | trapezoid(w, h, a1) | Trapezoid |
regularPolygon | regularPolygon(r, n) | N-sided regular polygon |
polygon | polygon(pts) | Custom polygon |
slot | slot(w, h, angle=0, mode="a") | Slot-shaped face |
Sketch Refinement
| Method | Signature | Description |
|---|---|---|
fillet | fillet(d) | Round sketch corners |
chamfer | chamfer(d) | Bevel sketch corners |
finalize | finalize() | Complete sketch and return parent |
Import / Export
| Operation | Syntax |
|---|---|
| Import STEP | importers.importStep("path.step") |
| Import DXF | importers.importDXF("path.dxf", tol=1e-6) |
| Export (auto) | exporters.export(solid, "path.step") |
| Export STL | exporters.export(solid, "path.stl", tolerance=0.01) |
| Export SVG | solid.exportSvg("path.svg") |
Supported formats: STEP, STL, AMF, SVG, VRML, GLTF, TJS
Assemblies
assy = (
cq.Assembly()
.add(part1, name="base", color=cq.Color("red"))
.add(part2, name="lid", loc=cq.Location((0, 0, 10)))
.constrain("base@faces@>Z", "lid@faces@<Z", "Plane")
.solve()
)
assy.save("assembly.step")| Method | Description |
|---|---|
Assembly() | Create a new assembly |
.add(obj, loc, name, color) | Add a component |
.constrain(q1, q2, kind) | Apply a constraint |
.solve() | Resolve constraints |
.save(path) | Export (STEP, XML, GLTF, VTKJS, VRML) |
BREP Topology
| Term | Description |
|---|---|
| Vertex | A single point in space |
| Edge | A curve between two vertices |
| Wire | A collection of connected edges |
| Face | A surface bounded by edges/wires |
| Shell | A collection of connected faces |
| Solid | A closed shell (has interior) |
| Compound | A collection of solids |
Selector String Reference
Axis Symbols
| Symbol | Class | Meaning |
|---|---|---|
| `\ | ` | ParallelDirSelector |
# | PerpendicularDirSelector | Perpendicular to axis |
+ / - | DirectionSelector | Positive / negative direction |
> | DirectionMinMaxSelector | Maximum in direction |
< | DirectionMinMaxSelector | Minimum in direction |
% | TypeSelector | Geometry type |
>> | CenterNthSelector | Nth by center (high→low) |
<< | CenterNthSelector | Nth by center (low→high) |
Axes: X, Y, Z, XY, YZ, XZ, or custom >(1,1,0)
Face Selector Examples
| Selector | Returns |
|---|---|
>Z | Top face (max Z) |
<Z | Bottom face (min Z) |
| `\ | Z` |
+Z | Faces with +Z normal |
#Z | Faces perpendicular to Z (side faces) |
%Plane | All planar faces |
>>Z[1] | 2nd highest face by center |
Edge Selector Examples
| Selector | Returns |
|---|---|
| `\ | Z` |
| `\ | X` |
>Y | Edge(s) farthest in +Y |
#Z | Horizontal edges (perp. to Z) |
%Line | Straight edges only |
%Circle | Circular edges only |
Vertex Selector Examples
| Selector | Returns |
|---|---|
>Y | Vertices farthest in +Y |
<Y | Vertices closest in -Y |
>>Y[-2] | 2nd farthest vertex in +Y |
<<Y[0] | Closest vertex in -Y |
Combining Selectors
| Syntax | Meaning |
|---|---|
| `"\ | Z and >Y"` |
">Z or <Z" | Top or bottom |
"not >Z" | All faces except the top |
| `"\ | Z exc >Z"` |
Workplane Positioning
| Method | Description |
|---|---|
translate(Vector(x,y,z)) | Move object |
rotateAboutCenter(axisEnd, degrees) | Rotate around object center |
rotate(axisStart, axisEnd, degrees) | Rotate around arbitrary axis |
.faces(">Z").workplane() | New workplane on a face |
Workplane("XY", origin=(0,0,5)) | Offset workplane origin |
Named Planes
| Name | Normal | Equivalent |
|---|---|---|
XY | +Z | front |
XZ | +Y | top |
YZ | +X | right |
back | -Z | — |
bottom | -Y | — |
left | -X | — |
Core Classes
| Class | Description |
|---|---|
Workplane(inPlane, origin) | Primary modeling entry point |
Sketch(parent, locs) | 2D sketch builder |
Assembly(obj, loc, name) | Hierarchical assembly |
Plane(origin, xDir, normal) | 2D coordinate system |
Vector(x, y, z) | 3D direction/point |
Location(pt) | 3D position + orientation |
Color(r, g, b, a) | RGBA color |
Related
- Workplane 2D Operations
- Workplane 3D Operations
- Selectors
- Assemblies
File Management and Export
Importing and exporting CAD files in CadQuery. Supports STEP, STL, DXF, SVG, AMF, VRML, GLTF, and more.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane.toSvg | Workplane.toSvg(opts=None) | Return SVG text representing the first stack item |
Workplane.exportSvg | Workplane.exportSvg(fileName) | Export the first stack item as an SVG file |
importers.importStep | importers.importStep(fileName) | Load a STEP file into a CadQuery Workplane |
importers.importDXF | importers.importDXF(filename, tol=1e-6, exclude=[], include=[]) | Load a DXF file into a Workplane |
exporters.export | exporters.export(w, fname, exportType=None, tolerance=0.1, angularTolerance=0.1, opt=None) | Export a Workplane or Shape to a file |
DxfDocument | occ_impl.exporters.dxf.DxfDocument(approx=None, tolerance=1e-3) | Create a DXF document from CadQuery objects |
Signature / Usage
import cadquery as cq
from cadquery import exporters, importers
# Import a STEP file
result = importers.importStep("model.step")
# Export to STEP
exporters.export(result, "output.step")
# Export to STL with tolerance
exporters.export(result, "output.stl", tolerance=0.01, angularTolerance=0.1)
# Export to SVG
result.exportSvg("output.svg")
# Import DXF
profile = importers.importDXF("profile.dxf", tol=1e-6)Options / Props
exporters.export(w, fname, exportType, tolerance, angularTolerance, opt)
| Name | Type | Description |
|---|---|---|
w | `Workplane \ | Shape` |
fname | str | Output file path |
exportType | `str \ | None` |
tolerance | float | Linear tessellation tolerance for mesh-based formats (default 0.1) |
angularTolerance | float | Angular tessellation tolerance in radians (default 0.1) |
opt | `dict \ | None` |
importers.importDXF(filename, tol, exclude, include)
| Name | Type | Description |
|---|---|---|
filename | str | Path to the DXF file |
tol | float | Geometry reconstruction tolerance (default 1e-6) |
exclude | list[str] | Layer names to exclude |
include | list[str] | Layer names to include (empty = all layers) |
Workplane.toSvg(opts)
| Name | Type | Description |
|---|---|---|
opts | `dict \ | None` |
DxfDocument(approx, tolerance)
| Name | Type | Description |
|---|---|---|
approx | `str \ | None` |
tolerance | float | Approximation tolerance (default 1e-3) |
Supported Export Formats
| Format | Extension | Notes |
|---|---|---|
| STEP | .step, .stp | Standard geometry exchange; preserves topology |
| STL | .stl | Tessellated mesh; controlled by tolerance |
| AMF | .amf | XML-based additive manufacturing format |
| SVG | .svg | 2D projection for documentation |
| VRML | .vrml, .wrl | Virtual Reality scene format |
| GLTF | .gltf, .glb | Modern 3D web/viewer format |
| TJS | .json | Three.js JSON format |
Notes
exporters.export()auto-detects the format from the file extension whenexportTypeisNone.- Lower
tolerancevalues produce finer STL/AMF meshes but larger files and slower export. importers.importStep()returns aWorkplanewith the imported shape on the stack.- DXF import creates wire/face geometry from 2D DXF entities; 3D DXF is not supported.
Related
- Workplane Initialization
- Assemblies
Iteration Methods
Methods for applying a function to each item on the CadQuery stack.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane.each | each(callback, useLocalCoordinates=False, combine=False, clean=True) | Run a function on each stack value, collect return values |
Workplane.eachpoint | eachpoint(arg, useLocalCoordinates=False, combine=False, clean=True) | Like each(), but the callback receives a Location-translated copy |
Signature / Usage
import cadquery as cq
# Use each() to apply a custom operation at every stack point
def make_pillar(loc):
return cq.Workplane("XY").circle(0.25).extrude(2).val().located(loc)
result = (
cq.Workplane("XY")
.rarray(2, 2, 3, 3)
.each(make_pillar, combine=True)
)
# eachpoint: callback receives translated location objects
def make_pin(loc):
return cq.Workplane("XY").circle(0.1).extrude(1).val().located(loc)
result = (
cq.Workplane("XY")
.rarray(1, 1, 4, 4)
.eachpoint(make_pin, useLocalCoordinates=True, combine=True)
)Options / Props
Workplane.each(callback, useLocalCoordinates, combine, clean)
| Name | Type | Description |
|---|---|---|
callback | Callable[[Shape], Shape] | Function called for each stack item; receives the shape and must return a Shape |
useLocalCoordinates | bool | Transform the shape into the current workplane's local coordinate system before passing to callback (default False) |
combine | `bool \ | str` |
clean | bool | Run clean() on the result (default True) |
Workplane.eachpoint(arg, useLocalCoordinates, combine, clean)
| Name | Type | Description |
|---|---|---|
arg | Callable[[Location], Shape] | Function called for each stack location; receives a Location object |
useLocalCoordinates | bool | Use local coordinate system for the location (default False) |
combine | `bool \ | str` |
clean | bool | Run clean() on the result (default True) |
Notes
each()is suited for operating on existing shapes;eachpoint()is better when generating new geometry at each location.- The callback must return a
Shape(orCompound), not aWorkplane. - Use
.val()inside the callback to extract theShapefrom aWorkplanebuilder. useLocalCoordinates=Truetransforms coordinates into the workplane frame, enabling consistent relative placement.
Related
- Stack and Selector Methods
- 2D Operations
- 3D Operations (Requiring 2D Workplane)
CadQuery API Reference
| Name | Description | Path |
|---|---|---|
| Sketch Initialization | Creating and initializing Sketch objects; Sketch(), importDXF, finalize, copy, located, moved | ./sketch-initialization.md |
| Sketch Selection | Selecting, tagging, and deleting sketch elements; tag, select, reset, delete, faces, edges, vertices | ./sketch-selection.md |
| Sketching with Faces | Face-based sketch primitives and arrays; rect, circle, ellipse, rarray, parray, fillet, chamfer, hull, offset | ./sketch-faces.md |
| Sketching with Edges and Constraints | Edge construction and constraint solver; segment, arc, spline, close, assemble, constrain, solve | ./sketch-edges-constraints.md |
| Workplane Initialization | Creating Workplanes with named planes or custom Plane objects | ./workplane-initialization.md |
| 2D Operations | All 2D drawing methods: lines, arcs, shapes, arrays; lineTo, rect, circle, rarray, polarArray, spline | ./workplane-2d-operations.md |
| 3D Operations (Requiring 2D Workplane) | 3D solids and Booleans from 2D profiles; extrude, revolve, loft, sweep, hole, box, union, cut | ./workplane-3d-operations.md |
| 3D Operations (Not Requiring 2D Workplane) | Direct solid modifications; fillet, chamfer, shell, split, rotate, translate, mirror | ./workplane-3d-non-2d.md |
| File Management and Export | Import/export for STEP, STL, DXF, SVG, GLTF; importStep, importDXF, exporters.export | ./file-management.md |
| Iteration Methods | Apply callbacks across stack items; each, eachpoint | ./iteration-methods.md |
| Stack and Selector Methods | Stack navigation and geometry selection; faces, edges, vertices, val, end, add | ./stack-selector-methods.md |
| Selectors | Selector classes and string syntax; >Z, `\ | X, %Plane, NearestToPointSelector, AreaNthSelector` |
| Assemblies | Hierarchical assemblies with constraints; Assembly, add, constrain, solve, save, Color | ./assemblies-api.md |
| Cheatsheet | Quick-reference for all major operations, selectors, and patterns | ./cheatsheet.md |
Selectors
Selector classes and string syntax for filtering CadQuery geometry (faces, edges, vertices, etc.).
String Selector Syntax
Selectors can be passed as strings directly to .faces(), .edges(), .vertices(), etc.
Axis Modifiers
| Symbol | Class | Meaning | Example |
|---|---|---|---|
| `\ | ` | ParallelDirSelector | Parallel to axis |
# | PerpendicularDirSelector | Perpendicular to axis | #Z — faces perpendicular to Z |
+ | DirectionSelector | Aligned in positive direction | +X — faces with +X normal |
- | DirectionSelector | Aligned in negative direction | -Y — faces with -Y normal |
> | DirectionMinMaxSelector | Maximum in direction | >Z — topmost face |
< | DirectionMinMaxSelector | Minimum in direction | <Z — bottommost face |
% | TypeSelector | Geometry type | %Plane — planar faces only |
>> | CenterNthSelector | Nth by center in direction | >>Z[1] — 2nd-highest face by center |
<< | CenterNthSelector | Nth by center in neg. direction | <<Z[0] — lowest face by center |
Axis References
X, Y, Z, XY, YZ, XZ — or a custom vector >(1, 1, 0)
Combining Selectors
| Operator | Meaning | Example |
|---|---|---|
and | Intersection | `"\ |
or | Union | ">Z or <Z" |
not | Inversion | "not >Z" |
exc / except | Exclude | `"\ |
Selector Classes
| Class | Signature | Description |
|---|---|---|
NearestToPointSelector | NearestToPointSelector(pnt) | Select the object nearest to the provided point |
BoxSelector | BoxSelector(point0, point1, boundingbox=False) | Select objects inside a 3D bounding box |
BaseDirSelector | BaseDirSelector(vector, tolerance=1.0) | Base class for direction-based selectors |
ParallelDirSelector | ParallelDirSelector(vector, tolerance=1.0) | Select objects parallel to the direction |
DirectionSelector | DirectionSelector(vector, tolerance=1.0) | Select objects aligned with the direction |
DirectionNthSelector | DirectionNthSelector(vector, n, directionMax=True, tolerance=0.01) | Select the Nth object sorted by direction |
LengthNthSelector | LengthNthSelector(n, directionMax=True, tolerance=1e-3) | Select the object(s) with Nth length |
AreaNthSelector | AreaNthSelector(n, directionMax=True, tolerance=1e-3) | Select the object(s) with Nth area |
RadiusNthSelector | RadiusNthSelector(n, directionMax=True, tolerance=1e-3) | Select the object with the Nth radius |
PerpendicularDirSelector | PerpendicularDirSelector(vector, tolerance=1.0) | Select objects perpendicular to the direction |
TypeSelector | TypeSelector(typeString) | Select objects with the given geometry type |
DirectionMinMaxSelector | DirectionMinMaxSelector(vector, directionMax=True, tolerance=0.01) | Select the object closest or farthest in direction |
CenterNthSelector | CenterNthSelector(vector, n, directionMax=True, tolerance=0.01) | Sort by center projection and return the Nth object |
BinarySelector | BinarySelector(left, right) | Base class for two-selector operations |
AndSelector | AndSelector(left, right) | Intersection of two selector results |
SumSelector | SumSelector(left, right) | Union of two selector results |
SubtractSelector | SubtractSelector(left, right) | Difference of two selector results |
InverseSelector | InverseSelector(selector) | Invert a selector's results |
StringSyntaxSelector | StringSyntaxSelector(selectorString) | Parse and apply a string-syntax selector |
Signature / Usage
import cadquery as cq
from cadquery.selectors import NearestToPointSelector, AreaNthSelector
# String selector - top face
result = cq.Workplane("XY").box(4, 4, 4).faces(">Z")
# Select largest face
result = cq.Workplane("XY").box(4, 4, 2).faces(AreaNthSelector(-1))
# Combine string selectors
result = cq.Workplane("XY").box(4, 4, 4).edges("|Z and >Y")
# Use NearestToPointSelector
result = (
cq.Workplane("XY")
.box(4, 4, 4)
.faces(NearestToPointSelector((0, 0, 2)))
)Face Filtering Examples
| Selector | Returns |
|---|---|
>Z | Topmost face (max Z) |
<Z | Bottommost face (min Z) |
| `\ | Z` |
+Z | Faces with +Z normal |
#Z | Faces perpendicular to Z (i.e. side faces) |
%Plane | All planar faces |
>>Z[1] | 2nd face from top by center |
Edge Filtering Examples
| Selector | Returns |
|---|---|
| `\ | Z` |
>Y | Edge(s) farthest in +Y |
#Z | Edges perpendicular to Z |
%Line | Linear edges only |
TypeSelector Types
| String | Geometry |
|---|---|
"Plane" | Planar faces |
"Cylinder" | Cylindrical faces |
"Sphere" | Spherical faces |
"Cone" | Conical faces |
"Line" | Linear edges |
"Circle" | Circular edges |
"Ellipse" | Elliptical edges |
Notes
DirectionNthSelectorandCenterNthSelectoruse zero-based indexn; negative indices count from the end.BoxSelector(boundingbox=False)tests whether the object's center is inside the box;boundingbox=Truetests whether the bounding box intersects.- For non-planar faces, direction-based selectors are evaluated at the center of mass.
- Combining selectors via string syntax is often clearer than nesting
AndSelector/SumSelectorobjects.
Related
- Stack and Selector Methods
- Cheatsheet
Sketching with Edges and Constraints
Edge-based sketch construction with geometric constraint support in CadQuery.
Method Summary
| Method | Signature | Description |
|---|---|---|
Sketch.edge | Sketch.edge(val, tag=None, forConstruction=False) | Add an edge object directly to the sketch |
Sketch.segment | Sketch.segment(p1, p2, tag=None, forConstruction=False) | Construct a line segment between two points |
Sketch.arc | Sketch.arc(p1, p2, p3, tag=None, forConstruction=False) | Construct a three-point arc |
Sketch.spline | Sketch.spline(pts, tangents=None, periodic=False, tag=None, forConstruction=False) | Construct a spline through given points |
Sketch.close | Sketch.close(tag=None) | Connect the last edge back to the first edge |
Sketch.assemble | Sketch.assemble(mode="a", tag=None) | Assemble open edges into closed face(s) |
Sketch.constrain | Sketch.constrain(tag1, tag2, constraint, arg) | Add a geometric constraint between tagged edges |
Sketch.solve | Sketch.solve() | Solve current constraints and update edge positions |
Signature / Usage
import cadquery as cq
# Edge-based workflow with constraints
result = (
cq.Workplane("XY")
.sketch()
.segment((0, 0), (1, 0), tag="bottom")
.segment((1, 0), (1, 1), tag="right")
.segment((1, 1), (0, 1), tag="top")
.close()
.assemble(mode="a")
.finalize()
.extrude(0.5)
)Options / Props
Sketch.edge(val, tag, forConstruction)
| Name | Type | Description |
|---|---|---|
val | Edge | Edge object to add |
tag | `str \ | None` |
forConstruction | bool | Mark as construction geometry (not included in face) |
Sketch.segment(p1, p2, tag, forConstruction)
| Name | Type | Description |
|---|---|---|
p1 | tuple[float, float] | Start point (x, y) |
p2 | tuple[float, float] | End point (x, y) |
tag | `str \ | None` |
forConstruction | bool | Mark as construction geometry |
Sketch.arc(p1, p2, p3, tag, forConstruction)
| Name | Type | Description |
|---|---|---|
p1 | tuple[float, float] | Start point |
p2 | tuple[float, float] | Midpoint on arc |
p3 | tuple[float, float] | End point |
tag | `str \ | None` |
forConstruction | bool | Mark as construction geometry |
Sketch.spline(pts, tangents, periodic, tag, forConstruction)
| Name | Type | Description |
|---|---|---|
pts | list[tuple] | Ordered list of points the spline passes through |
tangents | `list[tuple] \ | None` |
periodic | bool | Create a closed periodic spline |
tag | `str \ | None` |
forConstruction | bool | Mark as construction geometry |
Sketch.constrain(tag1, tag2, constraint, arg)
| Name | Type | Description |
|---|---|---|
tag1 | str | Tag of first edge |
tag2 | str | Tag of second edge |
constraint | str | Constraint type (e.g. "Coincident", "Angle", "Length", "Distance", "Horizontal", "Vertical", "Tangent") |
arg | `float \ | None` |
Notes
- Edges must form a closed loop before calling
Sketch.assemble()to build a face. Sketch.close()is a convenience shortcut that adds the final segment to close the loop.Sketch.solve()must be called after adding all constraints to update geometry positions.- Construction edges (forConstruction=True) are used as references for constraints but are not part of the resulting face.
- Constraints are solved using a 2D constraint solver; over- or under-constrained sketches will raise an error.
Related
- Sketch Initialization
- Sketch Selection
- Sketching with Faces
Sketching with Faces
Face-based sketch construction API — create closed-face primitives, arrays, and perform local modifications within a CadQuery sketch.
Method Summary
| Method | Signature | Description |
|---|---|---|
Sketch.face | Sketch.face(b, angle=0, mode="a", tag=None, ignore_selection=False) | Construct a face from a wire or edges |
Sketch.rect | Sketch.rect(w, h, angle=0, mode="a", tag=None) | Construct a rectangular face |
Sketch.circle | Sketch.circle(r, mode="a", tag=None) | Construct a circular face |
Sketch.ellipse | Sketch.ellipse(a1, a2, angle=0, mode="a", tag=None) | Construct an elliptical face |
Sketch.trapezoid | Sketch.trapezoid(w, h, a1, a2=None, angle=0, mode="a", tag=None) | Construct a trapezoidal face |
Sketch.slot | Sketch.slot(w, h, angle=0, mode="a", tag=None) | Construct a slot-shaped face |
Sketch.regularPolygon | Sketch.regularPolygon(r, n, angle=0, mode="a", tag=None) | Construct a regular N-sided polygonal face |
Sketch.polygon | Sketch.polygon(pts, angle=0, mode="a", tag=None) | Construct a polygonal face from points |
Sketch.rarray | Sketch.rarray(xs, ys, nx, ny) | Generate a rectangular array of locations |
Sketch.parray | Sketch.parray(r, a1, da, n, rotate=True) | Generate a polar array of locations |
Sketch.distribute | Sketch.distribute(n, start=0, stop=1, rotate=True) | Distribute locations along selected edges or wires |
Sketch.each | Sketch.each(callback, mode="a", tag=None, ignore_selection=False) | Apply a callback on all applicable entities |
Sketch.push | Sketch.push(locs, tag=None) | Set current selection to given locations or points |
Sketch.hull | Sketch.hull(mode="a", tag=None) | Generate a convex hull from the current selection or all objects |
Sketch.offset | Sketch.offset(d, mode="a", tag=None) | Offset selected wires or edges by distance d |
Sketch.fillet | Sketch.fillet(d) | Add a fillet to the current selection |
Sketch.chamfer | Sketch.chamfer(d) | Add a chamfer to the current selection |
Sketch.clean | Sketch.clean() | Remove internal wires from faces |
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY")
.sketch()
.rect(4, 2) # outer rectangle face
.rarray(1.5, 0.75, 2, 2) # 2x2 grid of locations
.circle(0.25, mode="s") # subtract circles at each location
.reset()
.vertices()
.fillet(0.25)
.finalize()
.extrude(0.5)
)Options / Props
Common mode parameter
| Value | Meaning |
|---|---|
"a" | Add (union) to the sketch |
"s" | Subtract from the sketch |
"i" | Intersect with the sketch |
"c" | Construction (not included in final face) |
Sketch.rect(w, h, angle, mode, tag)
| Name | Type | Description |
|---|---|---|
w | float | Width |
h | float | Height |
angle | float | Rotation angle in degrees (default 0) |
mode | str | Boolean mode (default "a") |
tag | `str \ | None` |
Sketch.rarray(xs, ys, nx, ny)
| Name | Type | Description |
|---|---|---|
xs | float | X spacing between elements |
ys | float | Y spacing between elements |
nx | int | Number of elements in X |
ny | int | Number of elements in Y |
Sketch.parray(r, a1, da, n, rotate)
| Name | Type | Description |
|---|---|---|
r | float | Radius of the polar array |
a1 | float | Starting angle in degrees |
da | float | Angular spacing in degrees |
n | int | Number of elements |
rotate | bool | Rotate each element to face outward (default True) |
Sketch.distribute(n, start, stop, rotate)
| Name | Type | Description |
|---|---|---|
n | int | Number of locations to distribute |
start | float | Parameter start along edge/wire (0–1, default 0) |
stop | float | Parameter stop along edge/wire (0–1, default 1) |
rotate | bool | Align elements tangent to the edge (default True) |
Sketch.offset(d, mode, tag)
| Name | Type | Description |
|---|---|---|
d | float | Offset distance (positive = outward) |
mode | str | Boolean mode (default "a") |
tag | `str \ | None` |
Notes
- Array methods (
rarray,parray,distribute,push) set the current location context; subsequent face-creation calls are placed at each location. mode="s"is the primary way to create holes/cutouts within a sketch.Sketch.clean()removes leftover internal wires that can interfere with extrusion.Sketch.hull()wraps all selected geometry in a convex hull face.
Related
- Sketch Initialization
- Sketch Selection
- Sketching with Edges and Constraints
Sketch Initialization
Methods and classes for creating and initializing 2D sketch objects in CadQuery.
Method Summary
| Method | Signature | Description |
|---|---|---|
Sketch | Sketch(parent=None, locs=[], obj=None) | Construct a 2D sketch object |
Sketch.importDXF | Sketch.importDXF(filename, tol=1e-6, exclude=[], include=[]) | Import a DXF file and construct face(s) |
Workplane.sketch | Workplane.sketch() | Initialize and return a new sketch attached to the workplane |
Sketch.finalize | Sketch.finalize() | Finish sketch construction and return the parent workplane |
Sketch.copy | Sketch.copy() | Create a partial copy of the sketch |
Sketch.located | Sketch.located(loc) | Create a partial copy of the sketch at a new location |
Sketch.moved | Sketch.moved(*args) | Create a partial copy of the sketch with moved faces |
Signature / Usage
import cadquery as cq
# Create a sketch via Workplane
result = (
cq.Workplane("XY")
.sketch()
.circle(1)
.finalize()
.extrude(1)
)
# Import DXF into a sketch
sketch = cq.Sketch().importDXF("profile.dxf")Options / Props
Sketch(parent, locs, obj)
| Name | Type | Description |
|---|---|---|
parent | `Workplane \ | None` |
locs | list[Location] | Initial locations for repeated placement |
obj | `Shape \ | None` |
Sketch.importDXF(filename, tol, exclude, include)
| Name | Type | Description |
|---|---|---|
filename | str | Path to the DXF file |
tol | float | Tolerance for geometry reconstruction (default 1e-6) |
exclude | list[str] | Layer names to exclude |
include | list[str] | Layer names to include (empty = all) |
Sketch.located(loc)
| Name | Type | Description |
|---|---|---|
loc | Location | New location for the sketch copy |
Notes
Sketch.finalize()must be called to return control to the parentWorkplaneafter sketch operations.Sketch.copy()/Sketch.located()/Sketch.moved()produce shallow copies suitable for reuse in arrays.- Use
Workplane.sketch()as the primary entry point when building sketches within a fluent chain.
Related
- Sketch Selection
- Sketching with Faces
- Sketching with Edges and Constraints
Sketch Selection
Methods for selecting, tagging, and manipulating elements within a CadQuery sketch.
Method Summary
| Method | Signature | Description |
|---|---|---|
Sketch.tag | Sketch.tag(tag) | Tag the current selection for later recall |
Sketch.select | Sketch.select(*tags) | Select elements based on previously assigned tags |
Sketch.reset | Sketch.reset() | Clear the current selection |
Sketch.delete | Sketch.delete() | Delete the currently selected objects |
Sketch.faces | Sketch.faces(s=None, tag=None) | Select faces, optionally filtered |
Sketch.edges | Sketch.edges(s=None, tag=None) | Select edges, optionally filtered |
Sketch.vertices | Sketch.vertices(s=None, tag=None) | Select vertices, optionally filtered |
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY")
.sketch()
.circle(2).tag("outer")
.circle(1).tag("inner")
.select("outer") # re-select the outer circle
.faces() # work with face selection
.finalize()
)Options / Props
Sketch.tag(tag)
| Name | Type | Description |
|---|---|---|
tag | str | Label to assign to the current selection |
Sketch.select(*tags)
| Name | Type | Description |
|---|---|---|
*tags | str | One or more tag names to select |
Sketch.faces(s, tag) / Sketch.edges(s, tag) / Sketch.vertices(s, tag)
| Name | Type | Description |
|---|---|---|
s | `str \ | Selector \ |
tag | `str \ | None` |
Notes
- Tags survive subsequent operations and can be referenced at any later point in the sketch chain.
Sketch.reset()restores selection to "all objects" — useful before starting a new selection sequence.Sketch.delete()permanently removes the selected geometry from the sketch; use with care.- All three geometry-type selectors (
faces,edges,vertices) accept the samesandtagarguments.
Related
- Sketch Initialization
- Sketching with Faces
- Sketching with Edges and Constraints
Stack and Selector Methods
Methods for navigating, querying, and modifying the object stack and selecting geometry on a CadQuery Workplane.
Method Summary
Stack Navigation
| Method | Signature | Description |
|---|---|---|
Workplane.all | all() | Return a list of all CQ objects on the stack |
Workplane.size | size() | Return the number of objects currently on the stack |
Workplane.vals | vals() | Get the raw values (Shapes) in the current list |
Workplane.val | val() | Return the first value on the stack |
Workplane.first | first() | Return the first item (as Workplane) on the stack |
Workplane.item | item(i) | Return the ith item on the stack |
Workplane.last | last() | Return the last item on the stack |
Workplane.end | end(n=1) | Return the nth parent of this CQ element |
Workplane.add | add(obj) | Add an object or list of objects to the stack |
Geometry Selectors
| Method | Signature | Description |
|---|---|---|
Workplane.vertices | vertices(selector=None, tag=None) | Select vertices, optionally filtered |
Workplane.faces | faces(selector=None, tag=None) | Select faces, optionally filtered |
Workplane.edges | edges(selector=None, tag=None) | Select edges, optionally filtered |
Workplane.wires | wires(selector=None, tag=None) | Select wires, optionally filtered |
Workplane.solids | solids(selector=None, tag=None) | Select solids, optionally filtered |
Workplane.shells | shells(selector=None, tag=None) | Select shells, optionally filtered |
Workplane.compounds | compounds(selector=None, tag=None) | Select compounds, optionally filtered |
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY")
.box(4, 4, 4)
.faces(">Z") # select top face
.workplane() # new workplane on that face
.circle(1)
.cutBlind(2)
)
# Stack navigation
box = cq.Workplane("XY").box(2, 2, 2)
print(box.size()) # 1
print(type(box.val())) # <class 'cadquery.occ_impl.shapes.Solid'>
# Traverse parent chain
child = box.faces(">Z")
parent = child.end() # returns to the box workplaneOptions / Props
Geometry selector methods (faces, edges, vertices, wires, solids, shells, compounds)
| Name | Type | Description |
|---|---|---|
selector | `str \ | Selector \ |
tag | `str \ | None` |
Workplane.end(n)
| Name | Type | Description |
|---|---|---|
n | int | Number of levels to go up in the parent chain (default 1) |
Workplane.item(i)
| Name | Type | Description |
|---|---|---|
i | int | Zero-based index into the stack |
Workplane.add(obj)
| Name | Type | Description |
|---|---|---|
obj | `Shape \ | Workplane \ |
Notes
val()returns the first rawShape;vals()returns all raw shapes as a list. Both skip non-shape items.all()returns a list ofWorkplaneobjects wrapping each stack item individually.- Selector strings follow CadQuery's string syntax (see Selectors).
- Chaining
.faces(">Z").workplane()is the standard pattern for placing features on a specific face. end()is essential in fluent chains: after a.faces()selector, call.end()to return to the parent solid context.
Related
- Selectors
- Workplane Initialization
- Iteration Methods
2D Operations
2D drawing and construction methods on a CadQuery Workplane, used to build wire profiles for subsequent 3D operations.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane.center | center(x, y) | Shift local coordinates to the specified location |
Workplane.lineTo | lineTo(x, y, forConstruction=False) | Draw a line from current point to absolute (x, y) |
Workplane.line | line(xDist, yDist, forConstruction=False) | Draw a line by relative distance from current point |
Workplane.vLine | vLine(distance, forConstruction=False) | Draw a vertical line by the given distance |
Workplane.vLineTo | vLineTo(yCoord, forConstruction=False) | Draw a vertical line to an absolute y coordinate |
Workplane.hLine | hLine(distance, forConstruction=False) | Draw a horizontal line by the given distance |
Workplane.hLineTo | hLineTo(xCoord, forConstruction=False) | Draw a horizontal line to an absolute x coordinate |
Workplane.polarLine | polarLine(distance, angle, forConstruction=False) | Draw a line of given length at the given angle |
Workplane.polarLineTo | polarLineTo(distance, angle, forConstruction=False) | Draw a line to given polar coordinates |
Workplane.moveTo | moveTo(x=0, y=0) | Move the current point to (x, y) without drawing |
Workplane.move | move(xDist=0, yDist=0) | Move the current point by relative distance without drawing |
Workplane.spline | spline(listOfXYTuple, tangents=None, periodic=False, scale=True, tol=None, forConstruction=False, includeCurrent=False, makeWire=False) | Create a spline through the provided 2D or 3D points |
Workplane.parametricCurve | parametricCurve(func, N=400, start=0, stop=1, tol=1e-6, minDeg=1, maxDeg=6, smoothing=None, makeWire=True) | Create a spline curve approximating a parametric function |
Workplane.parametricSurface | parametricSurface(func, N=25, start=0, stop=1, tol=1e-3, minDeg=1, maxDeg=6, smoothing=None) | Create a spline surface approximating a parametric function |
Workplane.threePointArc | threePointArc(point1, point2, forConstruction=False) | Draw an arc through point1 (mid), ending at point2 |
Workplane.sagittaArc | sagittaArc(endPoint, sag, forConstruction=False) | Draw an arc defined by its sagitta (bulge) value |
Workplane.radiusArc | radiusArc(endPoint, radius, forConstruction=False) | Draw an arc defined by radius to the endpoint |
Workplane.tangentArcPoint | tangentArcPoint(endpoint, forConstruction=False, relative=True) | Draw an arc tangent to the previous edge ending at endpoint |
Workplane.mirrorY | mirrorY() | Mirror all pending edges around the Y axis of the workplane |
Workplane.mirrorX | mirrorX() | Mirror all pending edges around the X axis of the workplane |
Workplane.wire | wire(forConstruction=False) | Connect pending edges into a single wire |
Workplane.rect | rect(xLen, yLen, centered=True, forConstruction=False) | Make a rectangle for each item on the stack |
Workplane.circle | circle(radius, forConstruction=False) | Make a circle for each item on the stack |
Workplane.ellipse | ellipse(x_radius, y_radius, rotation_angle=0, forConstruction=False) | Make an ellipse for each item on the stack |
Workplane.ellipseArc | ellipseArc(x_radius, y_radius, angle1=360, angle2=360, rotation_angle=0, sense=1, forConstruction=False, startAtCurrent=True, makeWire=False) | Draw an elliptical arc |
Workplane.polyline | polyline(listOfXYTuple, forConstruction=False, includeCurrent=False) | Create a polyline from a list of points |
Workplane.close | close() | Close the current wire by connecting back to the start |
Workplane.rarray | rarray(xSpacing, ySpacing, xCount, yCount, center=True) | Create a rectangular array of points on the stack |
Workplane.polarArray | polarArray(radius, startAngle, angle, count, fill=True, rotate=True) | Create a polar array of points on the stack |
Workplane.slot2D | slot2D(length, diameter, angle=0) | Create a rounded slot for each point on the stack |
Workplane.offset2D | offset2D(d, kind="arc", forConstruction=False) | Create a 2D offset wire |
Workplane.placeSketch | placeSketch(*sketches) | Place the provided Sketch object(s) based on current stack items |
Signature / Usage
import cadquery as cq
# Draw a closed profile and extrude
result = (
cq.Workplane("XY")
.moveTo(0, 0)
.lineTo(2, 0)
.lineTo(2, 1)
.lineTo(0, 1)
.close()
.extrude(0.5)
)
# Rectangular array of circles
result = (
cq.Workplane("XY")
.rarray(1.5, 1.5, 3, 3)
.circle(0.25)
.extrude(1)
)Options / Props
Workplane.rect(xLen, yLen, centered, forConstruction)
| Name | Type | Description |
|---|---|---|
xLen | float | Length in X direction |
yLen | float | Length in Y direction |
centered | `bool \ | tuple[bool, bool]` |
forConstruction | bool | Create as construction geometry |
Workplane.spline(listOfXYTuple, tangents, periodic, ...)
| Name | Type | Description |
|---|---|---|
listOfXYTuple | list[tuple] | List of 2D or 3D points |
tangents | `list[tuple] \ | None` |
periodic | bool | Closed periodic spline |
includeCurrent | bool | Include the current point as the first spline point |
makeWire | bool | Return as a Wire rather than pending edge |
Workplane.rarray(xSpacing, ySpacing, xCount, yCount, center)
| Name | Type | Description |
|---|---|---|
xSpacing | float | Spacing between columns |
ySpacing | float | Spacing between rows |
xCount | int | Number of columns |
yCount | int | Number of rows |
center | `bool \ | tuple[bool, bool]` |
Workplane.polarArray(radius, startAngle, angle, count, fill, rotate)
| Name | Type | Description |
|---|---|---|
radius | float | Radius of the polar array |
startAngle | float | Starting angle in degrees |
angle | float | Total angular span in degrees |
count | int | Number of points |
fill | bool | Distribute evenly over the full angle span |
rotate | bool | Rotate each item to face outward |
Notes
- All coordinate arguments are in the local workplane coordinate system.
forConstruction=Truecreates geometry visible for reference but excluded from faces and wires.- Drawing methods accumulate "pending edges"; call
close()orwire()to consolidate them before 3D operations. mirrorX()/mirrorY()operate on all pending edges and are useful to draw half a profile.
Related
- Workplane Initialization
- 3D Operations (Requiring 2D Workplane)
- Stack and Selector Methods
3D Operations (Not Requiring 2D Workplane)
3D modification operations that work directly on selected solid geometry without requiring a 2D sketch profile.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane.shell | shell(thickness, kind="arc") | Hollow out a solid by removing selected faces and shelling |
Workplane.fillet | fillet(radius) | Fillet selected edges of a solid with the given radius |
Workplane.chamfer | chamfer(length, length2=None) | Chamfer selected edges of a solid |
Workplane.split | split(keepTop=False, keepBottom=False, keepBoth=False) | Split a solid along the active workplane |
Workplane.rotate | rotate(axisStartPoint, axisEndPoint, angleDegrees) | Return a copy of stack items rotated around an axis |
Workplane.rotateAboutCenter | rotateAboutCenter(axisEndPoint, angleDegrees) | Rotate stack items around their center by the given angle |
Workplane.translate | translate(vec) | Return a copy of stack items moved by a translation vector |
Workplane.mirror | mirror(mirrorPlane="XY", basePointVector=(0,0,0), union=False) | Mirror stack items about a plane |
Signature / Usage
import cadquery as cq
# Fillet all edges of a box
result = (
cq.Workplane("XY")
.box(4, 4, 4)
.edges("|Z")
.fillet(0.5)
)
# Shell a box (remove top face)
result = (
cq.Workplane("XY")
.box(4, 4, 4)
.faces(">Z")
.shell(0.2)
)
# Mirror a shape
result = (
cq.Workplane("XY")
.box(2, 2, 2)
.translate((3, 0, 0))
.mirror("YZ")
)Options / Props
Workplane.shell(thickness, kind)
| Name | Type | Description |
|---|---|---|
thickness | float | Wall thickness (positive = inward; negative = outward) |
kind | str | Offset type: "arc" (default), "intersection", "tangent" |
Workplane.fillet(radius)
| Name | Type | Description |
|---|---|---|
radius | float | Fillet radius |
Workplane.chamfer(length, length2)
| Name | Type | Description |
|---|---|---|
length | float | Chamfer length |
length2 | `float \ | None` |
Workplane.split(keepTop, keepBottom, keepBoth)
| Name | Type | Description |
|---|---|---|
keepTop | bool | Keep only the top portion |
keepBottom | bool | Keep only the bottom portion |
keepBoth | bool | Return both portions as a compound |
Workplane.rotate(axisStartPoint, axisEndPoint, angleDegrees)
| Name | Type | Description |
|---|---|---|
axisStartPoint | tuple[float, float, float] | Start point of the rotation axis |
axisEndPoint | tuple[float, float, float] | End point of the rotation axis |
angleDegrees | float | Rotation angle in degrees |
Workplane.mirror(mirrorPlane, basePointVector, union)
| Name | Type | Description |
|---|---|---|
mirrorPlane | `str \ | Plane \ |
basePointVector | `tuple \ | Vector` |
union | bool | Union the mirrored result with the original |
Notes
fillet()andchamfer()operate on the selected edges (set with.edges()prior to the call). Without prior selection, all edges are affected.shell()removes the selected faces to create openings; without a selection it attempts to shell with no opening.split()uses the active workplane as the cutting plane.translate()androtate()create new objects; they do not modify in-place.mirror(union=True)automatically unions the mirrored copy back into the original solid.
Related
- 3D Operations (Requiring 2D Workplane)
- Stack and Selector Methods
- Selectors
3D Operations (Requiring 2D Workplane)
3D solid creation and Boolean operations that use an active 2D workplane profile in CadQuery.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane.cboreHole | cboreHole(diameter, cboreDiameter, cboreDepth, depth=None, clean=True) | Make a counterbored hole for each item on the stack |
Workplane.cskHole | cskHole(diameter, cskDiameter, cskAngle, depth=None, clean=True) | Make a countersunk hole for each item on the stack |
Workplane.hole | hole(diameter, depth=None, clean=True) | Make a simple hole for each item on the stack |
Workplane.extrude | extrude(until, combine=True, clean=True, both=False, taper=None) | Create a prismatic solid by extruding pending wires |
Workplane.cut | cut(toCut, clean=True, tol=None) | Subtract a solid from the current solid |
Workplane.cutBlind | cutBlind(until, clean=True, both=False, taper=None) | Create a prismatic cut to a specified depth |
Workplane.cutThruAll | cutThruAll(clean=True, taper=0) | Create a prismatic cut completely through the solid |
Workplane.box | box(length, width, height, centered=True, combine=True, clean=True) | Create a 3D box |
Workplane.sphere | sphere(radius, direct=(0,0,1), angle1=-90, angle2=90, angle3=360, centered=True, combine=True, clean=True) | Create a 3D sphere |
Workplane.wedge | wedge(dx, dy, dz, xmin, zmin, xmax, zmax, pnt=(0,0,0), dir=(0,1,0), centered=True, combine=True, clean=True) | Create a 3D wedge |
Workplane.cylinder | cylinder(height, radius, direct=(0,0,1), angle=360, centered=True, combine=True, clean=True) | Create a cylinder |
Workplane.union | union(toUnion=None, clean=True, glue=False, tol=None) | Union the stack items with the current solid |
Workplane.combine | combine(clean=True, glue=False, tol=None) | Combine all stack items into a single solid |
Workplane.intersect | intersect(toIntersect, clean=True, tol=None) | Intersect the provided solid with the current solid |
Workplane.loft | loft(ruled=False, combine=True, clean=True) | Create a lofted solid through a set of wire profiles |
Workplane.sweep | sweep(path, multisection=False, makeSolid=True, isFrenet=False, combine=True, clean=True, transition="right", normal=None, auxSpine=None) | Sweep a profile along a path |
Workplane.twistExtrude | twistExtrude(distance, angleDegrees, combine=True, clean=True) | Extrude a profile while twisting by the given angle |
Workplane.revolve | revolve(angleDegrees=360, axisStart=None, axisEnd=None, combine=True, clean=True) | Revolve a wire profile around an axis to create a solid |
Workplane.text | text(txt, fontsize, distance, cut=True, halign="center", valign="center", font="Arial", fontPath=None, kind="regular", combine=False, clean=True) | Create 3D extruded text |
Signature / Usage
import cadquery as cq
# Extrude a rectangle
result = cq.Workplane("XY").rect(4, 2).extrude(1)
# Revolve a profile
result = (
cq.Workplane("XZ")
.lineTo(2, 0)
.lineTo(2, 3)
.lineTo(0, 3)
.close()
.revolve(360, (0, 0, 0), (0, 1, 0))
)
# Loft between two profiles
result = (
cq.Workplane("XY")
.rect(4, 4)
.workplane(offset=5)
.circle(1)
.loft()
)Options / Props
Workplane.extrude(until, combine, clean, both, taper)
| Name | Type | Description |
|---|---|---|
until | `float \ | str` |
combine | `bool \ | str` |
clean | bool | Run clean() after operation (default True) |
both | bool | Extrude in both directions |
taper | `float \ | None` |
Workplane.hole(diameter, depth, clean)
| Name | Type | Description |
|---|---|---|
diameter | float | Hole diameter |
depth | `float \ | None` |
clean | bool | Run clean() after operation |
Workplane.cboreHole(diameter, cboreDiameter, cboreDepth, depth, clean)
| Name | Type | Description |
|---|---|---|
diameter | float | Through-hole diameter |
cboreDiameter | float | Counterbore diameter |
cboreDepth | float | Counterbore depth |
depth | `float \ | None` |
clean | bool | Run clean() after operation |
Workplane.sweep(path, multisection, ...)
| Name | Type | Description |
|---|---|---|
path | `Wire \ | Workplane` |
multisection | bool | Use multiple wire profiles from the stack |
isFrenet | bool | Use Frenet frame for orientation |
transition | str | Transition mode: "right", "round", "transformed" |
normal | `Vector \ | None` |
auxSpine | `Wire \ | None` |
Workplane.revolve(angleDegrees, axisStart, axisEnd, combine, clean)
| Name | Type | Description |
|---|---|---|
angleDegrees | float | Angle of revolution (default 360) |
axisStart | `tuple \ | None` |
axisEnd | `tuple \ | None` |
combine | bool | Union with existing solid |
clean | bool | Run clean() after operation |
Notes
extrude(until="next")andextrude(until="last")use face topology to determine depth automatically.- Boolean operations (
cut,union,intersect) accept either aWorkplaneorShapeargument. combine=True(default) merges the new solid with the existing one on the stack;combine=Falseleaves separate solids.clean=True(default) callsSolid.clean()to heal the result, which can be slow for complex geometry.loft()requires at least two wire profiles on the stack (created withworkplane()calls between them).
Related
- 2D Operations
- 3D Operations (Not Requiring 2D Workplane)
- Workplane Initialization
Initialization (Workplane)
Creating new Workplanes and starting object chains in CadQuery.
Method Summary
| Method | Signature | Description |
|---|---|---|
Workplane | Workplane(inPlane="XY", origin=(0,0,0), obj=None) | Define a coordinate system in space for 2D/3D operations |
Signature / Usage
import cadquery as cq
# Named plane
wp = cq.Workplane("XY")
wp = cq.Workplane("YZ")
wp = cq.Workplane("XZ")
wp = cq.Workplane("front")
wp = cq.Workplane("back")
wp = cq.Workplane("top")
wp = cq.Workplane("bottom")
wp = cq.Workplane("left")
wp = cq.Workplane("right")
# Custom plane with origin offset
wp = cq.Workplane("XY", origin=(0, 0, 10))
# Workplane from an existing Plane object
plane = cq.Plane(origin=(0, 0, 5), xDir=(1, 0, 0), normal=(0, 0, 1))
wp = cq.Workplane(plane)Options / Props
Workplane(inPlane, origin, obj)
| Name | Type | Description |
|---|---|---|
inPlane | `str \ | Plane` |
origin | tuple[float, float, float] | Origin offset for the workplane in world coordinates (default (0, 0, 0)) |
obj | `Shape \ | None` |
Named Planes Reference
| Name | Normal Direction | X Direction |
|---|---|---|
XY / front | +Z | +X |
XZ / top | +Y | +X |
YZ / right | +X | +Y |
back | -Z | +X |
bottom | -Y | +X |
left | -X | +Y |
Notes
- The
Workplaneis the primary entry point for all CadQuery fluent API operations. - Operations are performed in the local 2D coordinate system of the active workplane.
- Use
Workplane.workplane()(stack method) to create a new workplane offset from an existing face or plane after initial construction. - All coordinates passed to 2D drawing methods are relative to the active workplane origin and axes.
Related
- 2D Operations
- 3D Operations (Requiring 2D Workplane)
- Stack and Selector Methods
Assembly Colors
cq.Color assigns display colors to assembly parts. Accepts RGBA tuples or named color strings.
Signature / Usage
import cadquery as cq
# Named color
cq.Color("black")
cq.Color("yellow")
cq.Color("green")
# RGBA tuple (values 0.0–1.0; alpha controls transparency)
cq.Color(0, 0, 1, 0.2) # semi-transparent blue
cq.Color(1, 0, 0, 1.0) # opaque red
# Used in Assembly.add()
assy.add(shape, name="part", color=cq.Color("steelblue"))
assy.add(panel, name="panel", color=cq.Color(0, 0, 1, 0.2))Options / Props
cq.Color(r, g, b, a=1.0) or cq.Color(name)
| Parameter | Type | Description |
|---|---|---|
r, g, b | float (0–1) | Red, green, blue channels |
a | float (0–1) | Alpha (opacity); 1.0 = fully opaque |
name | str | Named color string (OCCT color names) |
Notes
- Over 700 named colors are available (OCCT X11 color set).
- Common names:
"red","green","blue","black","white","yellow","gray","steelblue","orange","cyan","magenta","gold","pink","violet","brown","coral","ivory","khaki","lavender","salmon","silver","tan","teal","turquoise". - Gray variants are available as
"gray0"through"gray99". - Color is a display property only; it does not affect geometry or solver behavior.
Related
- tutorial.md
Constraints
Constraint types available for Assembly.constrain(). Each defines a cost function that solve() minimizes.
Signature / Usage
# String-selector form
assy.constrain("part1@faces@>Z", "part2@faces@<Z", "Plane")
assy.constrain("part1@faces@<X", "part2@faces@<X", "Axis", param=0)
# Shape-object form (for BoxSelector or custom selectors)
assy.constrain("part1", part1.faces(">Z").val(), "part2", part2.faces("<Z").val(), "Axis")
# Single-object constraints (Fixed family)
assy.constrain("part1", "Fixed")
assy.constrain("part1@faces@>Z", "FixedAxis", (1, 0, 0))
assy.constrain("part1", "FixedPoint", (0, 0, 5))
assy.constrain("part1", "FixedRotation", (45, 0, 90))Constraint Types
Two-object constraints
| Constraint | param default | Description |
|---|---|---|
"Point" | 0 | Minimizes distance between centers of the two objects. param sets target distance; use a dummy Vertex for directional offsets. |
"Axis" | 180 | Minimizes angle between direction vectors. 180 → mate (surfaces touch, normals opposite). 0 → same direction (pin through hole). Direction is extracted via normalAt() for Face, normal() for circular Edge, tangentAt() for other Edge. |
"Plane" | 180 (Axis part) | Shortcut combining Point + Axis. Use for face-to-face mating. param applies to the Axis component. |
"PointInPlane" | 0 | Centers first object on the plane defined by second object. param offsets the plane along its normal. |
"PointOnLine" | 0 | Centers first object on the line defined by second object. param sets the distance from the line. |
Single-object constraints
| Constraint | param | Description |
|---|---|---|
"Fixed" | — | Locks all 6 degrees of freedom (3 translation + 3 rotation). |
"FixedPoint" | (x, y, z) | Locks all translational DOF; pins center to the given point. |
"FixedRotation" | (rx, ry, rz) | Locks all rotational DOF; pins orientation to given Euler angles (degrees). |
"FixedAxis" | (ax, ay, az) | Locks 2 rotational DOF by fixing the normal/tangent of the selected face/edge to the given direction. |
Notes
- The string selector syntax is
"partName@subtype@directionSelector"(e.g.,"left@faces@<Z") or"partName?tagName"for tagged shapes. "Plane"is equivalent to applying"Point"+"Axis"together and is the most common mating constraint.- Only
Face, circularEdge, and non-circularEdgeare valid for"Axis"; other types raiseValueError. - Systems can be underconstrained (solver may not move unconstrained parts) or overconstrained (solver finds best fit).
Related
- tutorial.md
- locations.md
Object Locations
cq.Location specifies translation and rotation when adding parts to an assembly.
Signature / Usage
import cadquery as cq
cone = cq.Solid.makeCone(1, 0, 2)
assy = cq.Assembly()
# Add with explicit location: translation tuple, axis tuple, angle (degrees)
assy.add(
cone,
loc=cq.Location((0, 0, 0), (1, 0, 0), 180),
name="cone0",
color=cq.Color("green"),
)
# Add at default location (origin, no rotation)
assy.add(cone, name="cone1", color=cq.Color("blue"))
show_object(assy)cq.Location(translation, axis, angle)
| Parameter | Type | Description |
|---|---|---|
translation | tuple[float, float, float] | (x, y, z) offset |
axis | tuple[float, float, float] | Rotation axis vector |
angle | float | Rotation angle in degrees |
Notes
- Locations set via
loc=in.add()are overwritten bysolve()when constraints are present. - In underconstrained systems the solver may not move an object that doesn't contribute to any cost function; its initial location is then preserved.
- For complicated assemblies, supplying approximately correct initial locations can reduce solver computation time.
- Use constraints +
solve()as the preferred alternative to manually computing locations.
Related
- tutorial.md
- constraints.md
Assemblies
| Name | Description | Path |
|---|---|---|
| Assembly Tutorial | Step-by-step guide: Assembly constructor, add(), constrain(), solve(), and export() | tutorial.md |
| Object Locations | Using cq.Location to set initial part positions and how solve() interacts with them | locations.md |
| Constraints | All constraint types (Point, Axis, Plane, PointInPlane, PointOnLine, Fixed, FixedPoint, FixedRotation, FixedAxis) with parameters | constraints.md |
| Assembly Colors | cq.Color with RGBA tuples and 700+ named color strings | colors.md |
Assembly Tutorial
Step-by-step guide to building a multi-part assembly using cq.Assembly, constraints, and solve().
Signature / Usage
import cadquery as cq
# Instantiate an assembly and add parts
assy = (
cq.Assembly()
.add(shape_or_workplane, name="part_name", color=cq.Color("black"), loc=cq.Location(...))
.add(...)
)
# Define constraints between parts
assy.constrain("part1@faces@>Z", "part2@faces@<Z", "Plane")
assy.constrain("part1@faces@<X", "part2@faces@<X", "Axis")
# Run the constraint solver
assy.solve()
# Export
assy.export("result.step") # STEP format
assy.export("result.xml") # OCCT XML formatOptions / Props
Assembly() constructor
| Name | Type | Default | Description |
|---|---|---|---|
name | str | None | Optional name for the root assembly |
loc | Location | identity | Initial location of the root assembly |
color | Color | None | Default color for the assembly |
.add(obj, ...)
| Name | Type | Default | Description |
|---|---|---|---|
obj | Shape / Workplane / Assembly | required | Shape to add |
name | str | auto-generated | Unique identifier for the part |
color | Color | None | Display color |
loc | Location | identity | Initial placement; overwritten by solve() |
.constrain(selector1, selector2, kind, param=...)
| Argument | Description |
|---|---|
selector1 | String "name@subtype@selector" or "name?tag", or (name, Shape) pair |
selector2 | Same as selector1 |
kind | Constraint type string: "Plane", "Axis", "Point", etc. |
param | Numeric parameter; meaning depends on constraint type |
Notes
- Tagged faces (
rv.faces(">X").tag("X")) can be referenced with"part?tag"syntax. solve()overwrites initial locations set withloc=; initial locations only influence convergence in underconstrained or multi-solution systems.- Shape objects can be passed directly instead of string selectors:
.constrain("p1", shape1, "p2", shape2, "Axis")— use.val()to extract a singleShapefrom aWorkplane.
Related
- locations.md
- constraints.md
- colors.md
Core Classes
CadQuery's four primary objects for 2D/3D modeling and assembly.
---
Sketch
A 2D sketch object for constructing planar geometry using edges, constraints, and faces.
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY")
.placeSketch(
cq.Sketch()
.rect(2, 2)
.circle(0.5, mode="s")
)
.extrude(1)
)Constructor
cadquery.Sketch(parent=None, locs=None, obj=None)In practice, cq.Sketch() is typically instantiated with no arguments and populated via method chaining.
Key Methods
| Method | Signature | Description |
|---|---|---|
rect | rect(w, h, angle=0, mode='a', tag=None) | Add a rectangle |
circle | circle(r, mode='a', tag=None) | Add a circle |
ellipse | ellipse(a1, a2, angle=0, mode='a', tag=None) | Add an ellipse |
polygon | polygon(n, r, angle=0, mode='a', tag=None) | Regular polygon by circumradius |
regularPolygon | regularPolygon(r, n, angle=0, mode='a', tag=None) | Regular polygon |
trapezoid | trapezoid(w, h, left_a, right_a=None, angle=0, mode='a', tag=None) | Trapezoid |
slot2D | slot2D(w, h, angle=0, mode='a', tag=None) | Slot shape |
segment | segment(p1, p2, tag=None) | Line segment between two points |
arc | arc(p1, p2, p3, tag=None) | Three-point arc |
bezier | bezier(pts, tag=None) | Bezier curve through control points |
spline | spline(pts, tangents=None, periodic=False, tag=None) | Spline through points |
close | close(tag=None) | Close the current open wire |
hull | hull(tags=None, mode='a', tag=None) | Convex hull of selected/tagged edges |
offset | offset(d, mode='a', tag=None) | Offset current edges |
fillet | fillet(d) | Fillet selected vertices |
chamfer | chamfer(d) | Chamfer selected vertices |
rarray | rarray(xs, ys, nx, ny) | Rectangular location array |
parray | parray(r, a, da, n) | Polar location array |
distribute | distribute(n) | Distribute along wire |
each | each(callback) | Apply callback to each location |
vertices | vertices(s=None, tag=None) | Select vertices |
edges | edges(s=None, tag=None) | Select edges |
wires | wires(s=None, tag=None) | Select wires |
faces | faces(s=None, tag=None) | Select faces |
tag | tag(name) | Tag current selection |
val | val() | Return current single value |
vals | vals() | Return all current values |
add | add(obj) | Add a shape to the sketch |
located | located(l) | Return sketch at given Location |
moved | moved(l) | Return sketch moved by Location |
copy | copy() | Copy the sketch |
delete | delete() | Delete selected entities |
constrain | constrain(tag1, tag2, constraint_type, arg) | Apply geometric constraint |
solve | solve() | Solve constraint system |
assemble | assemble(tag=None, mode='a') | Convert edges to faces |
finalize | finalize() | Return parent workplane with sketch |
export | export(path, *args, **kwargs) | Export sketch geometry |
importDXF | importDXF(filename, *args, **kwargs) | Import edges from DXF |
reset | reset() | Reset selection |
clean | clean() | Remove empty wires/edges |
Notes
- Most methods return
selffor fluent chaining. modeparameter controls how geometry is added:'a'(add),'s'(subtract),'i'(intersect),'c'(construction).- Use
finalize()to return to the parentWorkplaneafter building a sketch. solve()must be called afterconstrain()to compute positions.
Related
- topological.md
---
Workplane
Defines a coordinate system in 3D space from which 2D and 3D modeling operations are performed. The central class of the CadQuery fluent API.
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY")
.box(10, 10, 5)
.faces(">Z")
.workplane()
.hole(2)
)Constructor
cadquery.Workplane(
inPlane: str | Plane | Face = "XY",
origin: tuple | Vector = (0, 0, 0),
obj: Shape | None = None
)| Parameter | Type | Default | Description |
|---|---|---|---|
inPlane | `str \ | Plane \ | Face` |
origin | `tuple \ | Vector` | (0,0,0) |
obj | `Shape \ | None` | None |
Key Methods
Selection
| Method | Description |
|---|---|
vertices(selector=None, tag=None) | Select vertices |
edges(selector=None, tag=None) | Select edges |
wires(selector=None, tag=None) | Select wires |
faces(selector=None, tag=None) | Select faces |
shells(selector=None, tag=None) | Select shells |
solids(selector=None, tag=None) | Select solids |
compounds(selector=None, tag=None) | Select compounds |
all() | All objects on stack as list |
first() | First object on stack |
last() | Last object on stack |
item(i) | Object at index i |
ancestors(kind) | Ancestor shapes of the given type |
2D Sketching
| Method | Description |
|---|---|
moveTo(x, y) | Move to position without drawing |
move(xDist, yDist) | Relative move |
lineTo(x, y) | Line to absolute position |
line(xDist, yDist) | Line to relative position |
hLine(xDist) | Horizontal line |
vLine(yDist) | Vertical line |
hLineTo(xCoord) | Horizontal line to absolute x |
vLineTo(yCoord) | Vertical line to absolute y |
polyline(pts, includeCurrent=False, forConstruction=False) | Polyline through points |
spline(pts, tangents=None, periodic=False, parameters=None, scale=True, tol=None) | Spline through points |
bezier(pts, includeCurrent=False, forConstruction=False) | Bezier curve |
close() | Close current wire to form a loop |
circle(radius, forConstruction=False) | Circle at current point |
rect(xLen, yLen, centered=True, forConstruction=False) | Rectangle |
ellipse(x_radius, y_radius, rotation=0, forConstruction=False) | Ellipse |
polygon(nSides, diameter, forConstruction=False, circumscribed=False) | Regular polygon |
slot2D(length, diameter, angle=0) | Rounded slot |
rarray(xSpacing, ySpacing, xCount, yCount, center=True) | Rectangular array of locations |
polarArray(radius, startAngle, angle, count, fill=True, rotate=True) | Polar array of locations |
placeSketch(*sketches) | Place one or more sketches |
3D Modeling
| Method | Description |
|---|---|
box(length, width, height, centered=True, combine=True) | Box primitive |
cylinder(height, radius, direct=(0,0,1), angle=360, centered=True, combine=True) | Cylinder primitive |
sphere(radius, direct=(0,0,1), angle1=-90, angle2=90, angle3=360, centered=True, combine=True) | Sphere primitive |
wedge(dx, dy, dz, xmin, zmin, xmax, zmax, pnt=(0,0,0), dir=(0,0,1), centered=True, combine=True) | Wedge primitive |
extrude(distance, combine=True, clean=True, both=False, taper=None) | Extrude pending wires |
revolve(angleDegrees=360, axisStart=(0,0,0), axisEnd=(0,1,0), combine=True, clean=True) | Revolve pending wires |
loft(ruled=False, combine=True, clean=True) | Loft through pending wires |
sweep(path, multisection=False, sweepAlongWires=None, makeSolid=True, isFrenet=False, combine=True, clean=True, transition='right', normal=None, auxSpine=None) | Sweep along path |
hole(diameter, depth=None, clean=True) | Through or blind hole |
cboreHole(diameter, cboreDiameter, cboreDepth, depth=None, clean=True) | Counterbored hole |
cskHole(diameter, cskDiameter, cskAngle, depth=None, clean=True) | Countersunk hole |
cutBlind(distance, clean=True, both=False, taper=None) | Extrude-cut to depth |
cutThruAll(clean=True, both=False) | Extrude-cut through all |
shell(thickness, kind='arc') | Hollow out a solid |
fillet(radius) | Fillet selected edges |
chamfer(length, length2=None) | Chamfer selected edges |
mirror(mirrorPlane='XY', basePointVector=(0,0,0), union=False) | Mirror shapes |
rotate(axisStartPoint, axisEndPoint, angleDegrees) | Rotate shapes |
translate(vec) | Translate shapes |
scale(factor) | Scale shapes |
offset2D(d, kind='arc', forConstruction=False) | Offset 2D wires |
thicken(thickness, clean=True) | Thicken faces to solids |
Boolean Operations
| Method | Description |
|---|---|
cut(*toCut, combine=True, clean=True) | Boolean subtraction |
union(*toUnion, glue=False, combine=True, clean=True) | Boolean union |
intersect(*toIntersect, combine=True, clean=True) | Boolean intersection |
Navigation & Stack
| Method | Description |
|---|---|
workplane(offset=0, invert=False, centerOption='ProjectedOrigin', origin=None) | Create child workplane on selected face |
workplaneFromTagged(name) | Restore a tagged workplane |
tag(name) | Tag current state for later recall |
end(n=1) | Pop n levels up the chain |
newObject(objs) | Create new WP in chain with given objects |
add(obj) | Add object to current stack |
val() | Return first object on stack |
vals() | Return all objects on stack |
findSolid(searchStack=True, searchParents=True) | Find the active solid |
consolidateWires() | Merge all pending wires into one |
combine(clean=True, glue=False) | Combine all solids on stack |
Export
| Method | Description |
|---|---|
export(fname, *args, **kwargs) | Export to file (format inferred) |
exportSvg(fileName) | Export to SVG |
toOCC() | Return underlying OCC object |
toPending() | Add wires/edges to pending list |
sketch() | Switch to Sketch context |
Notes
- Almost all methods return a new
Workplaneto enable method chaining. - The string plane name
"XY"selects a named plane;"front","top","right"are aliases. selectorarguments accept either a string (parsed byStringSyntaxSelector) or aSelectorinstance.combine=Trueautomatically fuses results into the existing solid on the stack.
Related
- selectors.md
---
Assembly
Nested assembly of shapes, sub-assemblies, and relative positioning constraints.
Signature / Usage
import cadquery as cq
assy = (
cq.Assembly()
.add(cq.Workplane("XY").box(1, 1, 1), name="box")
.add(cq.Workplane("XY").sphere(0.5), name="ball", loc=cq.Location((0, 0, 1.5)))
)
assy.save("assembly.step")Constructor
cadquery.Assembly(
obj: Shape | Workplane | None = None,
loc: Location | None = None,
name: str | None = None,
color: Color | None = None,
material: Material | None = None,
metadata: Dict[str, Any] | None = None
)| Parameter | Type | Default | Description |
|---|---|---|---|
obj | `Shape \ | Workplane \ | None` |
loc | `Location \ | None` | None |
name | `str \ | None` | None |
color | `Color \ | None` | None |
material | `Material \ | None` | None |
metadata | `Dict[str, Any] \ | None` | None |
Key Methods
| Method | Signature | Description |
|---|---|---|
add | add(obj, loc=None, name=None, color=None, material=None) | Add a child shape or sub-assembly |
addSubshape | addSubshape(s, name=None, color=None, layer=None) | Add shape with metadata |
constrain | constrain(q1, q2=None, kind=None, param=None) | Add positional constraint between two parts |
solve | solve() | Solve all constraints and compute final positions |
remove | remove(name) | Remove a child by name |
toCompound | toCompound() | Return unified Compound with transformations applied |
traverse | traverse() | Generator yielding (name, assembly) pairs |
save | save(path, exportType=None, ...) | Save to STEP, GLTF, VRML, STL, etc. |
export | export(path, *args, **kwargs) | Alias for save |
importStep | importStep(path) (classmethod) | Load assembly from STEP file |
load | load(path) (classmethod) | Load from STEP, XML, or XBF |
Properties
| Name | Type | Description |
|---|---|---|
shapes | List[Shape] | Geometric objects in this assembly level |
Notes
- Constraint kinds include
"Plane","Point","Axis","Fixed"among others. solve()must be called beforetoCompound()orsave()when constraints are used.- Assembly
namevalues must be unique within the hierarchy. - Sub-assemblies can be nested arbitrarily deep via repeated
add()calls.
Related
- geometry.md
---
Constraint
An alias for ConstraintSpec, used internally by Assembly.constrain() to define positional relationships between components.
Signature / Usage
# Constraints are added via Assembly.constrain(), not instantiated directly:
assy.constrain("box?top_face", "ball?bottom_face", "Plane")
assy.solve()Notes
Constraintis an alias ofConstraintSpec— direct instantiation is rarely needed.- Constraints are resolved by calling
Assembly.solve(). - The query strings passed to
Assembly.constrain()use the form"<name>?<selector>".
Related
- core.md — Assembly
Geometry Classes
Geometric primitives and spatial data structures used throughout CadQuery.
---
Vector
A 3-dimensional vector supporting standard mathematical operations.
Signature / Usage
import cadquery as cq
v = cq.Vector(1, 0, 0)
n = v.normalized()
p = v.projectToPlane(cq.Vector(0, 0, 1))Constructor
cadquery.Vector(x: float = 0, y: float = 0, z: float = 0)
cadquery.Vector(v: tuple | list) # From 2- or 3-tuple
cadquery.Vector(v: gp_Vec | gp_Pnt | ...) # From OCC objectKey Methods
| Method | Return Type | Description |
|---|---|---|
multiply(scale) | Vector | Scalar multiplication |
normalized() | Vector | Unit vector in the same direction |
projectToLine(line_vector) | Vector | Project onto a line direction |
projectToPlane(plane_normal) | Vector | Project onto a plane by normal |
Center() (static) | Vector | Center (average) of a list of vectors |
Properties
| Name | Type | Description |
|---|---|---|
x | float | X component |
y | float | Y component |
z | float | Z component |
Length | float | Euclidean length |
Notes
- Supports
+,-,*,/,==operators. - Interoperable with Python tuples: most CadQuery methods accept
(x, y, z)tuples in place ofVector.
---
Matrix
A 4×4 homogeneous transformation matrix for 3D affine transforms.
Signature / Usage
import cadquery as cq
m = cq.Matrix()
row = m[0] # Access row as list
t = m.transposed_list()Constructor
cadquery.Matrix()Matrices are typically constructed by CadQuery internally (e.g., from Plane or Location objects).
Key Methods
| Method | Return Type | Description |
|---|---|---|
transposed_list() | List[List[float]] | Return 4×4 matrix as nested lists (column-major) |
__getitem__(index) | float | Access element by flat index |
Notes
- Wraps OpenCASCADE's
gp_Trsf/gp_Matobjects. - Pickle-serializable via
__getstate__/__setstate__.
---
Plane
A 2D coordinate system embedded in 3D space, defined by an origin, X direction, and normal.
Signature / Usage
import cadquery as cq
# Named planes
xy = cq.Plane.named("XY")
xz = cq.Plane.named("XZ")
# Custom plane
p = cq.Plane(origin=(0, 0, 5), xDir=(1, 0, 0), normal=(0, 0, 1))
# Coordinate conversion
world_pt = p.toWorldCoords((1, 2))
local_pt = p.toLocalCoords(cq.Vector(1, 2, 5))Constructor
cadquery.Plane(
origin: Vector | tuple,
xDir: Vector | tuple = (1, 0, 0),
normal: Vector | tuple = (0, 0, 1)
)| Parameter | Type | Default | Description |
|---|---|---|---|
origin | `Vector \ | tuple` | — |
xDir | `Vector \ | tuple` | (1,0,0) |
normal | `Vector \ | tuple` | (0,0,1) |
Key Methods
| Method | Return Type | Description |
|---|---|---|
named(name) (classmethod) | Plane | Create one of the standard named planes |
rotated(rotate=(0,0,0)) | Plane | Rotate plane around its axes |
setOrigin2d(x, y) | None | Shift the 2D origin within the plane |
toLocalCoords(obj) | `Vector \ | Shape` |
toWorldCoords(localpt) | Vector | Transform local (u,v) or (u,v,w) to world coordinates |
Properties
| Name | Type | Description |
|---|---|---|
origin | Vector | Origin point |
xDir | Vector | Local X axis direction |
yDir | Vector | Local Y axis direction (computed) |
zDir | Vector | Normal / Z axis direction |
Notes
- Named planes:
"XY","YZ","XZ","front","back","left","right","top","bottom". - Supports
==and!=for comparison; hashable for use in sets/dicts.
---
Location
A position and orientation in 3D space (translation + rotation).
Signature / Usage
import cadquery as cq
# From a translation vector
loc = cq.Location((1, 2, 3))
# From a plane (sets orientation)
loc = cq.Location(cq.Plane.XY)
# From vector + rotation axis + angle
loc = cq.Location(cq.Vector(0, 0, 10), cq.Vector(0, 0, 1), 45)
t = loc.toTuple() # ((x,y,z), (rx,ry,rz))Constructor
cadquery.Location(t: Any)Accepts: (x,y,z) tuple, Vector, Plane, OCC TopLoc_Location, or (translation, rotation) tuple.
Key Methods
| Method | Return Type | Description |
|---|---|---|
toTuple() | Tuple[Tuple[float,float,float], Tuple[float,float,float]] | ((x,y,z), (rx,ry,rz)) Euler angles in degrees |
Notes
Locationsupports*operator for composition and**-1for inversion.- Used extensively in
AssemblyandSketchfor positioning. - Pickle-serializable.
---
BoundBox
An axis-aligned bounding box for shapes or point sets.
Signature / Usage
import cadquery as cq
shape = cq.Workplane("XY").box(10, 5, 3).val()
bb = shape.BoundingBox()
print(bb.xmin, bb.xmax, bb.ymin, bb.ymax, bb.zmin, bb.zmax)Constructor
cadquery.BoundBox(bb: Bnd_Box)Typically obtained from Shape.BoundingBox(), not constructed directly.
Key Methods
| Method | Return Type | Description |
|---|---|---|
add(obj, tol=None) | BoundBox | Expand to include a point, Vector, or another BoundBox |
enlarge(tol) | BoundBox | Expand uniformly in all directions by tol |
isInside(b2) | bool | Check whether another BoundBox lies inside this one |
findOutsideBox2D(bb1, bb2) (static) | `BoundBox \ | None` |
Properties
| Name | Type | Description |
|---|---|---|
xmin | float | Minimum X |
xmax | float | Maximum X |
ymin | float | Minimum Y |
ymax | float | Maximum Y |
zmin | float | Minimum Z |
zmax | float | Maximum Z |
xsize | float | Width in X |
ysize | float | Width in Y |
zsize | float | Width in Z |
center | Vector | Center point |
DiagonalLength | float | Length of the space diagonal |
---
Color
An RGBA color wrapper around OpenCASCADE's Quantity_ColorRGBA.
Signature / Usage
import cadquery as cq
c1 = cq.Color("red") # Named color
c2 = cq.Color(1.0, 0.5, 0.0) # RGB, alpha=0
c3 = cq.Color(0.0, 1.0, 0.0, 0.5) # RGBA
rgba = c2.toTuple() # (1.0, 0.5, 0.0, 0.0)Constructor
cadquery.Color(name: str)
cadquery.Color(r: float, g: float, b: float, a: float = 0, srgb: bool = True)| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | — | CSS/OCC named color string |
r, g, b | float | — | Red, green, blue in [0, 1] |
a | float | 0 | Alpha in [0, 1] (0 = opaque) |
srgb | bool | True | Whether values are in sRGB color space |
Key Methods
| Method | Return Type | Description |
|---|---|---|
toTuple() | Tuple[float, float, float, float] | Return (r, g, b, a) |
Notes
- Supports
==and is hashable. - Alpha convention:
0= fully opaque,1= fully transparent (OCC convention).
---
Material
Material properties used in Assembly for simulation or export metadata.
Signature / Usage
import cadquery as cq
mat = cq.Material()
mat.name = "steel"
mat.density = 7850.0
mat.densityUnit = "kg/m^3"
mat.description = "Carbon steel"Constructor
cadquery.Material()Properties
| Name | Type | Description |
|---|---|---|
name | str | Material name |
density | float | Material density |
densityUnit | str | Unit string (e.g., "kg/m^3") |
description | str | Free-text description |
Key Methods
| Method | Return Type | Description |
|---|---|---|
toTuple() | tuple | Serialize to tuple |
Notes
- Supports
==, hashing, and pickle serialization. - Passed to
AssemblyorShapemetadata; not used for physical simulation by CadQuery itself.
CadQuery Class Reference
| Name | Description | Path |
|---|---|---|
| Core Classes | Sketch, Workplane, Assembly, Constraint — primary modeling objects | ./core.md |
| Topological Classes | Shape, Vertex, Edge, Wire, Face, Shell, Solid, Compound, CompSolid, Mixin1D, Mixin3D — OCC topology wrappers | ./topological.md |
| Geometry Classes | Vector, Matrix, Plane, Location, BoundBox, Color, Material — spatial primitives and data structures | ./geometry.md |
| Selector Classes | Selector and all derived types — filter topology by direction, type, size, position, or string expression | ./selectors.md |
Selector Classes
Selectors filter lists of topological objects (vertices, edges, faces, solids, etc.) returned by Workplane selection methods. They can be composed using binary operators.
---
Selector (Abstract Base)
Base class for all selectors. Defines the interface.
Signature / Usage
# Selectors are passed to Workplane selection methods:
result = cq.Workplane("XY").box(1,1,1).faces(cq.selectors.NearestToPointSelector((0,0,1)))Constructor
cadquery.selectors.Selector()Key Methods
| Method | Signature | Description |
|---|---|---|
filter | filter(objectList: List[Shape]) -> List[Shape] | Return the subset of objects passing the selector |
Notes
- Subclass and override
filter()to implement custom selectors. - Selectors support
|,&,-,!operators for composition (see Binary Selectors).
---
NearestToPointSelector
Selects the single object (vertex, edge, face, or solid) whose center is nearest to a given point.
Constructor
cadquery.selectors.NearestToPointSelector(pnt: tuple | Vector)| Parameter | Type | Description |
|---|---|---|
pnt | `tuple \ | Vector` |
Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Returns the single nearest object |
Notes
- Returns exactly one object: the closest by center-of-mass distance.
---
BoxSelector
Selects objects whose bounding box center lies within a 3D box defined by two corner points.
Constructor
cadquery.selectors.BoxSelector(
point0: tuple | Vector,
point1: tuple | Vector,
boundingbox: bool = False
)| Parameter | Type | Default | Description |
|---|---|---|---|
point0 | `tuple \ | Vector` | — |
point1 | `tuple \ | Vector` | — |
boundingbox | bool | False | If True, select objects whose bounding box overlaps the region |
Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Objects inside the box |
---
BaseDirSelector
Abstract base class for direction-based selectors.
Constructor
cadquery.selectors.BaseDirSelector(
vector: Vector | tuple,
tolerance: float = 0.0001
)Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Objects passing the directional test |
test(vec) | bool | Test a single direction vector |
Notes
- Override
test(vec)in subclasses to define the directional criterion.
---
DirectionSelector
Selects edges or faces whose normal/direction is aligned with (within tolerance of) the given vector.
Constructor
cadquery.selectors.DirectionSelector(
vector: Vector | tuple,
tolerance: float = 0.0001
)String syntax: "+X", "-Y", "+Z" etc. (positive/negative axis directions).
Notes
- For edges: selects edges parallel to the vector.
- For faces: selects faces whose normal matches the vector.
---
ParallelDirSelector
Selects objects whose direction is parallel (regardless of sign) to the given vector.
Constructor
cadquery.selectors.ParallelDirSelector(
vector: Vector | tuple,
tolerance: float = 0.0001
)String syntax: "|X", "|Y", "|Z".
Notes
- Differs from
DirectionSelectorin that anti-parallel (180°) also matches.
---
PerpendicularDirSelector
Selects objects whose direction is perpendicular to the given vector.
Constructor
cadquery.selectors.PerpendicularDirSelector(
vector: Vector | tuple,
tolerance: float = 0.0001
)String syntax: "#X", "#Y", "#Z".
---
DirectionMinMaxSelector
Selects the object(s) that are farthest (directionMax=True) or closest (directionMax=False) along a given direction.
Constructor
cadquery.selectors.DirectionMinMaxSelector(
vector: Vector | tuple,
directionMax: bool = True,
tolerance: float = 0.0001
)| Parameter | Type | Default | Description |
|---|---|---|---|
vector | `Vector \ | tuple` | — |
directionMax | bool | True | True = farthest (max), False = closest (min) |
tolerance | float | 0.0001 | Grouping tolerance |
String syntax: ">X", ">Y", ">Z" (max); "<X", "<Y", "<Z" (min).
Notes
- Uses center of mass for distance calculation.
- Multiple objects at the same extremal position are all returned.
---
DirectionNthSelector
Selects the Nth group of objects when sorted by their projection onto a direction vector.
Constructor
cadquery.selectors.DirectionNthSelector(
vector: Vector | tuple,
n: int,
directionMax: bool = True,
tolerance: float = 0.0001
)| Parameter | Type | Default | Description |
|---|---|---|---|
vector | `Vector \ | tuple` | — |
n | int | — | Index (0 = farthest if directionMax=True) |
directionMax | bool | True | Sort order direction |
tolerance | float | 0.0001 | Grouping tolerance |
String syntax: ">X[0]", "<Z[-1]" etc.
---
TypeSelector
Selects objects of a specific topological type.
Constructor
cadquery.selectors.TypeSelector(typeString: str)| Parameter | Type | Description |
|---|---|---|
typeString | str | One of: "Vertex", "Edge", "Wire", "Face", "Shell", "Solid", "Compound" |
String syntax: "%Plane" (planar faces), "%Line" (linear edges), "%Circle" (circular edges).
---
RadiusNthSelector
Selects the object(s) with the Nth smallest or largest radius among arc/circle edges.
Constructor
cadquery.selectors.RadiusNthSelector(
n: int,
directionMax: bool = True,
tolerance: float = 0.0001
)| Parameter | Type | Default | Description |
|---|---|---|---|
n | int | — | Rank index (0 = largest radius when directionMax=True) |
directionMax | bool | True | True = descending sort |
tolerance | float | 0.0001 | Grouping tolerance |
Key Methods
| Method | Return Type | Description |
|---|---|---|
key(obj) | float | Returns radius of the object (for sorting) |
---
CenterNthSelector
Selects the Nth object when sorted by the projection of its center onto a given direction.
Constructor
cadquery.selectors.CenterNthSelector(
vector: Vector | tuple,
n: int,
directionMax: bool = True,
tolerance: float = 0.0001
)String syntax: ">>X[0]", "<<Z[-1]" etc.
Key Methods
| Method | Return Type | Description |
|---|---|---|
key(obj) | float | Projected center distance along vector |
---
LengthNthSelector
Selects the Nth object when sorted by arc length (for edges/wires).
Constructor
cadquery.selectors.LengthNthSelector(
n: int,
directionMax: bool = True,
tolerance: float = 0.0001
)| Parameter | Type | Default | Description |
|---|---|---|---|
n | int | — | Rank index |
directionMax | bool | True | True = descending (longest first) |
tolerance | float | 0.0001 | Grouping tolerance |
Key Methods
| Method | Return Type | Description |
|---|---|---|
key(obj) | float | Arc length of the object |
---
AreaNthSelector
Selects the Nth object when sorted by surface area (for faces).
Constructor
cadquery.selectors.AreaNthSelector(
n: int,
directionMax: bool = True,
tolerance: float = 0.0001
)Key Methods
| Method | Return Type | Description |
|---|---|---|
key(obj) | float | Surface area of the object |
---
BinarySelector
Abstract base class for selectors that combine two child selectors.
Constructor
cadquery.selectors.BinarySelector(left: Selector, right: Selector)Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Apply both selectors and combine results |
---
AndSelector
Returns the intersection of two selectors (objects matching both).
Constructor
cadquery.selectors.AndSelector(left: Selector, right: Selector)String syntax: "<selectorA> and <selectorB>" or "<selectorA> & <selectorB>".
Signature / Usage
import cadquery as cq
result = (
cq.Workplane("XY").box(1, 1, 1)
.edges(cq.selectors.AndSelector(
cq.selectors.ParallelDirSelector((0, 0, 1)),
cq.selectors.LengthNthSelector(0)
))
)---
SumSelector
Returns the union of two selectors (objects matching either).
Constructor
cadquery.selectors.SumSelector(left: Selector, right: Selector)String syntax: "<selectorA> or <selectorB>" or "<selectorA> | <selectorB>".
---
SubtractSelector
Returns objects matching the left selector but not the right.
Constructor
cadquery.selectors.SubtractSelector(left: Selector, right: Selector)String syntax: "<selectorA> exc <selectorB>" or "<selectorA> except <selectorB>".
---
InverseSelector
Returns all objects that do NOT match a given selector.
Constructor
cadquery.selectors.InverseSelector(selector: Selector)String syntax: "not(<selectorString>)".
Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Objects that fail the wrapped selector |
---
StringSyntaxSelector
Parses and evaluates a compact string-based selector expression. Used internally by Workplane selection methods when a string argument is provided.
Signature / Usage
import cadquery as cq
# Equivalent pairs — string and explicit selector:
cq.Workplane("XY").box(1,1,1).faces(">Z")
cq.Workplane("XY").box(1,1,1).faces(cq.selectors.StringSyntaxSelector(">Z"))Constructor
cadquery.selectors.StringSyntaxSelector(selectorString: str)Key Methods
| Method | Return Type | Description |
|---|---|---|
filter(objectList) | List[Shape] | Evaluate string expression and return matching objects |
String Syntax Reference
Direction / alignment tokens
| Token | Meaning |
|---|---|
+X, +Y, +Z | Faces/edges aligned with positive axis |
-X, -Y, -Z | Faces/edges aligned with negative axis |
| `\ | X, \ |
#X, #Y, #Z | Perpendicular to axis |
>X, >Y, >Z | Farthest object in positive axis direction |
<X, <Y, <Z | Closest object (farthest in negative direction) |
>>X[n] | Nth object sorted by center projection (max direction) |
<<X[n] | Nth object sorted by center projection (min direction) |
>(x,y,z) | Farthest in custom direction vector |
Type tokens
| Token | Meaning |
|---|---|
%Plane | Planar faces |
%Line | Linear (straight) edges |
%Circle | Circular edges |
Indexed variants (ordinal selection)
>Z[0] # farthest (same as >Z)
>Z[-1] # second-farthest from negative end = second-closest
<Y[1] # second-closest in YComposite operators
| Operator | Meaning |
|---|---|
A and B or A & B | Intersection (AndSelector) |
A or B or `A \ | B` |
A exc B or A except B | Difference (SubtractSelector) |
not(A) | Inversion (InverseSelector) |
Notes
- String selectors are parsed at runtime; invalid tokens raise a
ValueError. - Custom direction vectors can be used:
">(1, 1, 0)". - Index notation
[n]supports negative indices (Python-style). StringSyntaxSelectoris the default when passing a plain string tofaces(),edges(), etc.
Topological Classes
Low-level wrappers around OpenCASCADE topology objects. All inherit from Shape.
---
Shape
Base class for all geometric objects in CadQuery. Wraps a TopoDS_Shape from OpenCASCADE.
Constructor
cadquery.Shape(obj: TopoDS_Shape)Key Methods
Topology Access
| Method | Return Type | Description |
|---|---|---|
Vertices() | List[Vertex] | All vertices |
Edges() | List[Edge] | All edges |
Wires() | List[Wire] | All wires |
Faces() | List[Face] | All faces |
Shells() | List[Shell] | All shells |
Solids() | List[Solid] | All solids |
Compounds() | List[Compound] | All compounds |
CompSolids() | List[CompSolid] | All compsolids |
Geometry Queries
| Method | Return Type | Description |
|---|---|---|
Area() | float | Surface area |
Volume() | float | Enclosed volume |
Center() | Vector | Center of mass |
CenterOfBoundBox(tolerance=None) | Vector | Center of bounding box |
CombinedCenter(objects) | Vector | Center over multiple shapes |
BoundingBox(tolerance=None) | BoundBox | Axis-aligned bounding box |
distance(other) | float | Minimum distance to another shape |
centerOfMass(obj) | Vector | Center of mass of OCC shape |
computeMass(obj) | float | Mass of OCC shape |
Transformations
| Method | Return Type | Description |
|---|---|---|
translate(vector) | Shape | Translate by vector |
rotate(startVector, endVector, angleDegrees) | Shape | Rotate around axis |
mirror(mirrorPlane, basePointVector) | Shape | Mirror across plane |
scale(factor) | Shape | Uniform scale |
move(loc) | Shape | Move by Location (in-place) |
moved(loc) | Shape | Return moved copy |
locate(loc) | Shape | Apply location (in-place) |
located(loc) | Shape | Return located copy |
Boolean Operations
| Method | Return Type | Description |
|---|---|---|
cut(*toCut, tol=None) | Shape | Boolean difference |
fuse(*toFuse, glue=False, tol=None) | Shape | Boolean union |
intersect(*toIntersect, tol=None) | Shape | Boolean intersection |
Utilities
| Method | Return Type | Description |
|---|---|---|
copy() | Shape | Deep copy |
isValid() | bool | Check topological validity |
isNull() | bool | Check if null/empty |
clean() | Shape | Remove redundant geometry |
fix() | Shape | Attempt to repair invalid geometry |
exportStep(fileName) | bool | Export to STEP file |
exportStl(fileName, tolerance, angularTolerance, ascii) | bool | Export to STL |
exportBrep(f) | bool | Export to BREP format |
export(fileName, exportType, ...) | Shape | Generic export |
Notes
Shapeis not instantiated directly; use the concrete subclasses.- Transformations return new
Shapeinstances; they do not mutate in-place unless explicitly noted.
---
Vertex
A single point in 3D space.
Constructor
cadquery.Vertex(obj: TopoDS_Shape, forConstruction: bool = False)| Parameter | Type | Default | Description |
|---|---|---|---|
obj | TopoDS_Shape | — | Underlying OCC vertex |
forConstruction | bool | False | If True, excluded from geometry operations |
Key Methods
| Method | Return Type | Description |
|---|---|---|
Center() | Vector | Position of this vertex as a Vector |
Related
- geometry.md — Vector
---
Edge
A trimmed curve that forms the border of a Face. Inherits Mixin1D and Shape.
Constructor
cadquery.Edge(obj: TopoDS_Shape)Key Methods
Factory / Creation (classmethods)
| Method | Description |
|---|---|
makeLine(v1, v2) | Straight line between two Vectors |
makeThreePointArc(v1, v2, v3) | Arc through three points |
makeTangentArc(v1, v2, v3) | Tangent arc |
makeSpline(listOfVector, tangents=None, periodic=False, parameters=None, scale=True, tol=1e-6) | Interpolating spline |
makeSplineApprox(listOfVector, tol=0.001, smoothing=None, minDeg=1, maxDeg=6) | Approximating spline |
makeBezier(points) | Cubic Bezier curve |
makeEllipse(x_radius, y_radius, pnt, dir, xdir, angle1=0, angle2=360, sense=1) | Ellipse or arc of ellipse |
Instance Methods
| Method | Return Type | Description |
|---|---|---|
arcCenter() | Vector | Center of underlying circle or ellipse |
hasPCurve(f) | bool | Whether edge has parametric curve on Face f |
close() | Edge | Close the edge to a loop |
trim(pmin, pmax) | Edge | Trim to parameter range |
Curve analysis methods inherited from Mixin1D are also available.
Notes
- Construction edges (
forConstruction=True) do not participate in face/wire building.
Related
- topological.md — Mixin1D
---
Wire
A series of connected, ordered Edges that typically bounds a Face. Inherits Mixin1D and Shape.
Constructor
cadquery.Wire(obj: TopoDS_Shape)Key Methods
Factory / Creation (classmethods)
| Method | Description |
|---|---|
makeCircle(radius, center, normal, angle1=0, angle2=360, sense=1) | Circular wire |
makeEllipse(x_radius, y_radius, pnt, dir, xdir, angle1=0, angle2=360, sense=1) | Ellipse wire |
makePolygon(listOfVectors, forConstruction=False, close=False) | Polygon wire |
makeHelix(pitch, height, radius, center=(0,0,0), dir=(0,0,1), angle=0) | Helical wire |
assembleEdges(edges) | Wire from an ordered list of edges |
Instance Methods
| Method | Return Type | Description |
|---|---|---|
Vertices() | List[Vertex] | Ordered vertices of the wire |
stitch(wires) | Wire | Stitch multiple wires into one |
combine(tolerance=1e-9) | List[Wire] | Merge colinear edges |
fillet(radius, vertices=None) | Wire | Fillet selected/all vertices |
fillet2D(radius, vertices) | Wire | 2D fillet in the XY plane |
chamfer2D(length, vertices) | Wire | 2D chamfer in the XY plane |
offset2D(d, kind='arc') | List[Wire] | 2D offset |
Notes
- A closed wire is required to create a
Face. assembleEdgesautomatically orders and joins edges.
---
Face
A bounded surface representing part of the boundary of a solid. Inherits Mixin3D and Shape.
Constructor
cadquery.Face(obj: TopoDS_Shape)Key Methods
Factory / Creation (classmethods)
| Method | Description |
|---|---|
makeFromWires(wire, *innerWires) | Face from outer wire, optionally with holes |
makeRuledSurface(edge1, edge2) | Ruled surface between two edges |
makeNSidedSurface(edges, *args) | N-sided surface (filling) |
makeSplineApprox(points, tol=0.01, smoothing=None, minDeg=1, maxDeg=3) | Surface approximation |
Query Methods
| Method | Return Type | Description |
|---|---|---|
Center() | Vector | Center of the face |
normalAt(locationVector=None) | Vector | Normal at given point |
positionAt(u, v) | Vector | Point at (u,v) parameters |
tangentAt(locationVector=None) | Vector | Tangent at given point |
paramAt(pt) | Tuple[float, float] | (u,v) parameters at given point |
locationAt(u, v) | Location | Location (pos + normal) at (u,v) |
uvBounds() | Tuple[float,float,float,float] | (umin, umax, vmin, vmax) |
toPln() | gp_Pln | Convert planar face to OCC plane |
isoline(isU, p) | Edge | Isoparametric line on surface |
Modification Methods
| Method | Return Type | Description |
|---|---|---|
fillet2D(radius, vertices) | Face | 2D fillet |
chamfer2D(length, vertices) | Face | 2D chamfer |
addHole(wire) | Face | Add hole to face |
thicken(thickness, solid=True) | Solid | Offset face to create a solid |
trim(umin, umax, vmin, vmax) | Face | Trim to parameter range |
extend(umin, umax, vmin, vmax) | Face | Extend beyond current bounds |
Related
- topological.md — Mixin3D
---
Shell
The outer boundary of a surface, formed from a connected set of Faces.
Constructor
cadquery.Shell(obj: TopoDS_Shape)Key Methods
| Method | Return Type | Description |
|---|---|---|
makeShell(listOfFaces) (classmethod) | Shell | Create shell from face list |
Notes
- Shells are rarely created directly; they arise from solid creation operations.
---
Solid
A single closed 3D volume. Inherits Mixin3D and Shape.
Constructor
cadquery.Solid(obj: TopoDS_Shape)Key Methods
Factory / Creation (classmethods)
| Method | Description |
|---|---|
makeBox(length, width, height, pnt=(0,0,0), dir=(0,0,1)) | Rectangular box |
makeSphere(radius, pnt=(0,0,0), dir=(0,0,1), angle1=-90, angle2=90, angle3=360) | Sphere |
makeCylinder(radius, height, pnt=(0,0,0), dir=(0,0,1), angle=360) | Cylinder |
makeCone(radius1, radius2, height, pnt=(0,0,0), dir=(0,0,1), angle=360) | Cone |
makeTorus(radius1, radius2, pnt=(0,0,0), dir=(0,0,1), angle=360) | Torus |
makeWedge(dx, dy, dz, xmin, zmin, xmax, zmax, pnt=(0,0,0), dir=(0,0,1)) | Wedge |
makeLoft(listOfWires, solid=True, ruled=False) | Loft through wire profiles |
makeSolid(shell) | Create solid from a closed shell |
Modification (instance methods)
| Method | Return Type | Description |
|---|---|---|
extrudeLinear(face, vecNormal, taper=0) | Solid | Linear extrusion |
extrudeLinearWithRotation(face, vecCenter, vecNormal, angleDegrees) | Solid | Extrude with twist |
revolve(face, angleDegrees, axisStart, axisEnd) | Solid | Revolve face about axis |
sweep(profile, path, makeSolid=True, isFrenet=False, mode=None, ...) | Solid | Sweep profile along path |
addCavity(tools, tol=None) | Solid | Subtract cavity shapes |
Query
| Method | Return Type | Description |
|---|---|---|
isSolid() | bool | Verify solid topology |
outerShell() | Shell | Outer boundary shell |
innerShells() | List[Shell] | Inner boundary shells (voids) |
Related
- topological.md — Mixin3D
---
Compound
A collection of disconnected shapes (solids, wires, edges, etc.). Inherits Mixin3D and Shape.
Constructor
cadquery.Compound(obj: TopoDS_Shape)Key Methods
| Method | Return Type | Description |
|---|---|---|
makeCompound(listOfShapes) (classmethod) | Compound | Create from list of shapes |
makeText(text, size, height, font='Arial', fontPath=None, kind='regular', halign='center', valign='center', position=Plane.XY) (classmethod) | Compound | 3D extruded text |
cut(*toCut, tol=None) | Compound | Boolean difference |
fuse(*toFuse, glue=False, tol=None) | Compound | Boolean union |
intersect(*toIntersect, tol=None) | Compound | Boolean intersection |
remove(*shape) | Compound | Remove shapes from compound |
ancestors(shape, kind) | Compound | Find ancestor shapes of given type |
siblings(shape, kind, level=1) | Compound | Find topologically related shapes |
__bool__() | bool | False if compound is empty |
Notes
Compoundis the result type of most multi-shape operations (e.g., arrays, text).
---
CompSolid
A composite solid — multiple solids sharing boundary faces.
Constructor
cadquery.CompSolid(obj: TopoDS_Shape)Notes
CompSolidis rarely used directly in CadQuery; it maps toTopoDS_CompSolidin OpenCASCADE.- Arises from some import operations on STEP files with shared topology.
---
Mixin1D
Mixin class providing parametric curve analysis methods for 1D shapes (Edge, Wire).
Key Methods
| Method | Return Type | Description |
|---|---|---|
bounds() | Tuple[float, float] | Parameter range (start, end) |
startPoint() | Vector | Point at start parameter |
endPoint() | Vector | Point at end parameter |
paramAt(pt) | float | Parameter at closest point to pt |
positionAt(d, mode='length') | Vector | 3D position at parameter/distance |
locationAt(d, mode='length', frame='frenet', planar=False) | Location | Location frame at parameter/distance |
tangentAt(d, mode='length') | Vector | Tangent direction at parameter/distance |
normalAt(d, mode='length') | Vector | Normal direction at parameter/distance |
curvatureAt(d, mode='length') | float | Signed curvature at parameter/distance |
radius() | float | Radius (circular edges only) |
arcCenter() | Vector | Center of circle/ellipse |
paramsLength() | float | Total arc length |
positions(ds, mode='length') | List[Vector] | Positions at multiple parameters |
tangents(ds, mode='length') | List[Vector] | Tangents at multiple parameters |
normals(ds, mode='length') | List[Vector] | Normals at multiple parameters |
curvatures(ds, mode='length') | List[float] | Curvatures at multiple parameters |
locations(ds, mode='length', frame='frenet', planar=False) | List[Location] | Locations at multiple parameters |
project(pt, d) | List[Vector] | Project external point onto curve |
sample(count) | List[Vector] | Evenly spaced sample points |
Notes
mode='length'interpretsdas arc length;mode='parameter'interprets it as the raw OCC parameter.frame='frenet'uses Frenet frame;frame='corrected'avoids discontinuities on helices.
---
Mixin3D
Mixin class providing post-processing operations for 3D shapes (Face, Shell, Solid, Compound).
Key Methods
| Method | Return Type | Description |
|---|---|---|
fillet(radius, edgeList=None) | Shape | Round specified (or all) edges |
chamfer(length, length2=None, edgeList=None) | Shape | Bevel specified (or all) edges |
hollow(thickness, faceList=None, tolerance=0.0001, kind='arc') | Shape | Hollow solid, removing specified faces |
dprism(basis, heights, depths, taper=0, draft=0) | Shape | Draft prism extrusion |
isInside(pt, tolerance=1e-6) | bool | Test if point is inside the shape |
Notes
filletandchamferoperate onedgeList; passNoneto apply to all edges.hollowis equivalent toWorkplane.shell().
Citing CadQuery
How to cite CadQuery in scientific research and publications.
Usage
When using CadQuery for scientific research, cite it via the official Zenodo DOI:
DOI: https://doi.org/10.5281/zenodo.3955118
Notes
- Use the Zenodo DOI link when referencing CadQuery in academic or scientific work
- Zenodo provides a persistent identifier suitable for formal citations and bibliographies
Related
- Misc README