Foundation (Python)ReferenceCheatsheet

Foundation cheatsheet

The same cheatsheet CADbuildr’s AI agents use, so it always matches what they write.

Use reliable primitives first, then compose.

  • Start from Part/Assembly and explicit Sketch planes.
  • Prefer clear, dimension-driven constants for repeatability.
  • Use Extrusion, Lathe, and Hole as the default operation set; Shell, Fillet, Chamfer, Loft, Sweep, Thread are below.
  • Keep transforms explicit with translate_*/rotate or TFHelper.
  • End scripts with a direct show(...) call for local validation.

Conventions

  • Units are mm. A 20 m building is 20000, not 20.
  • Extrusion(end, start) are absolute offsets along the plane normal, not lengths: Extrusion([s], 10, start=5) spans z 5→10 on xy(); end=-4 spans z −4→0.
  • Plane normals: xy() → +Z, xz() → −Y, yz() → +X (table under Planes).
  • direction= is a Point3D(x, y, z); only its direction counts — the distance is still end/start.
  • Primitive anchors (center = Point(sketch, u, v)): Box and Sphere are centred on it (Box spans ±h/2 along the normal); Cylinder sits on the plane and grows height along the normal (pass centered=True for ±height/2); Cone is centred (±height/2); Torus revolves about the sketch v-axis through center, not the normal — on xy() the ring stands up in XZ; for a flat ring around Z use Torus on xz() or yz().
  • Text needs no font: omit font_url and the kernel uses Roboto Regular. Baseline starts at the sketch origin.
  • Round / bevel the part’s edges like a CAD fillet: self.fillet_edges(r, edges=EdgeFinder(...)) / self.chamfer_edges(d, edges=...) work on the body built by every operation before them (no finder = all edges); later operations still apply on top. Modifiers on one feature: Shell/Fillet/Chamfer with a solid change only that op: if it is already in the part it is replaced in place, otherwise the modified solid is added like any other feature. Chain by nesting: Shell(Fillet(body, 5), 2). Macros (Box, Cylinder, Cone, Torus) must be .expand()ed first: Shell(Box(c, 40, 30, 20).expand(), 2).

Canonical imports

from cadbuildr.foundation import (
    Part,
    Assembly,
    Plane,
    Sketch,
    Point,
    Line,
    Axis,
    Polygon,
    Circle,
    Ellipse,
    Rectangle,
    Square,
    SVGShape,
    Lathe,
    Extrusion,
    Hole,
    Shell,
    Fillet,
    Chamfer,
    Loft,
    Sweep,
    Thread,
    Point3D,
    Helix3D,
    Spline3D,
    EdgeFinder,
    FaceFinder,
    Material,
    TFHelper,
    show,
)

Parts and assemblies

Rule: A Part is a single solid body — sculpt it with add_operation(...). An Assembly is a container of placed components — add children with add_component(component, tf=...). These do not mix: calling add_component(...) on a Part is invalid. To compose multiple solids, create an Assembly and add the Parts to it.

Rule (class constants): Part and Assembly are pydantic models, so a bare class-level attribute is treated as a model field and raises PydanticUserError: A non-annotated attribute was detected at class-definition time — the part never builds and nothing renders. Never write DIAMETER = 30 directly in the class body. Put dimensions in __init__ as instance attributes (preferred), or use module-level constants, or annotate true class constants with typing.ClassVar.

# WRONG — bare class attribute → PydanticUserError, part never renders
class Widget(Part):
    BASE_DIAMETER = 30              # ❌
 
# CORRECT — instance attribute (preferred for dimensions)
class Widget(Part):
    def __init__(self, base_diameter=30):
        super().__init__()
        self.base_diameter = base_diameter   # ✓
 
# CORRECT — module constant, or annotated ClassVar for a real constant
from typing import ClassVar
BASE_DIAMETER = 30                  # ✓ module level
class Widget(Part):
    BASE_DIAMETER: ClassVar[int] = 30        # ✓ annotated
Part() -> Part
Assembly() -> Assembly
Part.add_operation(operation) -> bool | None
Assembly.add_component(component, tf=None) -> bool | None
Assembly.check_interference(tolerance=0.0, allow=None, *, exact=False, volume_tol=1e-3, depth_tol=0.02) -> list[Interference]  # default: bounding boxes, jointed pairs exempt; exact=True: real solids via the kernel + manifold3d, jointed pairs checked (exempt with allow=[(a, b)]); line-to-line fits (shaft in same-size bore) stay clean

Joints place a child by mating anchors (make_anchor(name, pos, z_axis=...), +Z = mate axis); relations couple joint values (radians / mm, linear: driven = k·driver + offset, reverse=True negates; enforced at once, set either joint and both move; a DOF follows one relation, no cycles):

Assembly.add_joint(RevoluteJoint(parent_anchor, child_anchor, flip=BoolParameter(value=False)))  # also Rigid/Slider/Cylindrical/Planar/Ball/PinSlot/Screw
joint.set_angle(a) / joint.set_offset(d)                  # re-places the child + everything downstream
Assembly.add_relation(GearRelation(driver=j1, driven=j2, ratio=z1 / z2, reverse=True, offset=0.0))  # angle -> angle
Assembly.add_relation(RackPinionRelation(pinion=rev, rack=slider, pitch_radius=r))  # 2π·r mm of rack per turn
Assembly.add_relation(ScrewRelation(screw=rev, nut=slider, pitch=p))  # p mm per turn; nut omitted = a CylindricalJoint's own offset
Assembly.add_relation(LinearRelation(driver=s1, driven=s2, ratio=k))  # offset -> offset
Assembly.linear_pattern(component, direction, count, spacing) -> list  # copies of a PLACED component (deep copies, original first); jointed -> same joint on a derived parent anchor
Assembly.polar_pattern(component, count, angle_deg=360.0, axis=(0, 0, 1), center=(0, 0, 0), about=None) -> list  # about=Anchor: its +Z axis
Assembly.replicate(component, onto=[anchors], child_anchor="foot", flip=True) -> list  # one instance per anchor; unplaced -> RigidJoint to child_anchor, jointed -> its joint repeated
# WRONG — Part has no add_component
class Chair(Part):
    def __init__(self):
        super().__init__()
        self.add_component(Leg())       # ❌ TypeError
 
# CORRECT — single solid body stays a Part
class Leg(Part):
    def __init__(self):
        super().__init__()
        sketch = Sketch(self.xz())
        shape = Rectangle.from_center_and_sides(Point(sketch, 0, 0), 4, 40)
        self.add_operation(Extrusion([shape], 4))  # ✓
 
# CORRECT — compose multiple Parts inside an Assembly
class Chair(Assembly):
    def __init__(self):
        super().__init__()
        self.add_component(Leg())       # ✓

Anchors & joints (preferred over raw transforms)

# Anchor = named connector frame (+Z = mate axis / outward normal, +X = clocking)
part.add_anchor(make_anchor(name, position, z_down=False)) -> Anchor
part.anchor(name) -> Anchor
anchor.offset(translation) / anchor.rotated(angle, axis) / anchor.flipped() -> Anchor  # derived
 
# Joints place a child component by connecting two anchors (no transform math).
# flip=True (default) mates the anchors face-to-face.
assy.add_joint(RigidJoint(parent_anchor=a, child_anchor=b)) -> None
# Also: RevoluteJoint(angle)/SliderJoint(offset)/CylindricalJoint/PlanarJoint/
#       BallJoint/PinSlotJoint/ScrewJoint(pitch), each with optional JointLimits
assy.ground(component.anchor("base")) -> None  # fix to the assembly origin
joint.set_angle(a) / joint.set_offset(o)       # move a DOF, re-places the child + everything downstream
joint.resolve() / assembly.resolve()           # re-place after editing anchors by hand
 
# Connection = joint + geometry contributions (drill, mortise, cope...) in one call
assy.add_connection(Connection(joint=..., modifiers=[PartModifier(anchor=..., operations=[...])]))

Planes

(Part | Assembly).xy() -> Plane
(Part | Assembly).yz() -> Plane
(Part | Assembly).xz() -> Plane
Plane.get_parallel_plane(distance: float, name: str = "parallel") -> Plane | None
Plane.get_angle_plane_from_axis(axis: list[float], angle: float, name: str = "rotated") -> Plane | None

Where sketch coordinates land in world space (Point(sketch, u, v)), and which way a positive Extrusion(..., end) grows (the plane normal):

planesketch u →sketch v →extrudes toward
xy()+X+Y+Z
xz()+X+Z−Y
yz()+Y+Z+X

So a disc whose axis is world Y is a Circle on xz(), and Extrusion([c], 3) spans Y ∈ [−3, 0]. Plane.get_parallel_plane(d) offsets along that normal.

Sketches and elements

sketch = Sketch(plane)
Point(sketch, x, y) -> Point
Line(p1, p2) -> Line
Axis(line) -> Axis

Sketch shapes

Polygon(lines) -> Polygon
Polygon.from_points(sketch, points) -> Polygon  # closed; last->first edge added
CompactPolygon.from_points(sketch, [(x, y) | (x, y, bulge), ...])  # ONE node; bulge=tan(sweep/4) makes the edge leaving that vertex a true arc (bulge_from_sweep(deg))
CompactPolyline.from_points(sketch, points)  # open variant; use both for long outlines (racks, panels, cams)
Circle(center, radius) -> Circle
Ellipse(center, a, b) -> Ellipse
Rectangle.from_center_and_sides(center, w, h) -> Rectangle | None
Rectangle.from_2_corners(p1, p2) -> Rectangle | None
Rectangle.from_2_points(p1, p2) -> Rectangle | None  # legacy alias
Square.from_center_and_side(center, size) -> Square | None

SVG import in sketches

SVGShape(
    sketch,
    svg,
    xshift=0.0,
    yshift=0.0,
    angle=0.0,
    scale=1.0,
) -> CustomClosedShape
  • Use SVGShape to convert an SVG string into a sketch shape, then pass it to Extrusion or Lathe.
  • Keep viewBox explicit in the SVG string; the viewbox center maps to the sketch origin before shifts.
  • Supported SVG elements: path, text, rect, circle, ellipse, line, polygon.

STEP import

ImportStep(path_or_file, cut=False) -> ImportStep   # reads like open(): str/Path from cwd, or a file object
ImportStep.from_text(step_text, filename="inline.step") -> ImportStep
Part.from_step(path_or_file, name=None) -> Part     # a Part whose only operation is the import
  • A SolidOperation: self.add_operation(ImportStep("motor.step")) fuses it; it is a valid Fillet / Shell / BooleanOperation / MoveBody input; cut=True subtracts it.
  • The file’s text is stored in the node (with its sha256), so the DAG is self-contained; getting the file onto disk is up to you.
  • Units are converted from the file’s declared unit to mm; several solids are fused into one; place it with MoveBody.
  • Not STEP text (no ISO-10303-21; header) -> StepFileError; a file with no solid -> a build error naming the file.

Pencil API

Sketch exposes sketch.pencil for draw helpers.

sketch.pencil.move(dx, dy)
sketch.pencil.move_to(x, y)
sketch.pencil.line(dx, dy)
sketch.pencil.line_to(x, y)
sketch.pencil.arc(dx, dy, radius)
sketch.pencil.arc_to(x, y, radius)
sketch.pencil.tangent_arc(dx, dy)
sketch.pencil.tangent_arc_to(x, y)
sketch.pencil.rounded_corner_then_line(dx, dy, radius)
sketch.pencil.rounded_corner_then_line_to(x, y, radius)
sketch.pencil.get_closed_shape()
sketch.pencil.close_with_mirror()

Operations

Lathe(shape, axis, cut=False) -> Lathe
Extrusion([shape], end, start=0, cut=False, taper=0.0, direction=None) -> Extrusion  # direction: Point3D
Hole(point, radius, depth) -> Hole
Shell(solid, thickness, face_finder=None) -> Shell        # +t walls grow inward; default opens the top (max-Z) face
# Shell of a smooth Loft: if the surface offset fails, the wall is built from the sections offset in their planes (end sections only may be opened)
Fillet(solid, radius, edge_finder=None, radius_end=None, radius_points=None) -> Fillet       # no finder = all edges
# variable fillet: radius at each edge's start, radius_end at its end, radius_points=[FilletRadiusPoint(position, r)] between (0 < position < 1)
self.fillet_edges(radius, edges=None, radius_end=None, radius_points=None) -> Fillet     # edges of the part's body so far (CAD-style edge fillet); radius_points=[(0.5, 4)]
self.chamfer_edges(distance, edges=None) -> Chamfer # same, bevelled
Chamfer(solid, radius, edge_finder=None, distance2=None, angle_deg=None) -> Chamfer
# Chamfer / Fillet on one edge run on along every edge tangent to it (one straight edge of a rounded outline -> the whole outline)
self.chamfer_vertices(distance, at=None) -> VertexChamfer   # corner setback: cut convex 3-edge corners off (all, or at=[(x, y, z), ...])
VertexChamfer(solid, distance, vertices=None) -> VertexChamfer  # same on one feature; vertices=[Point3D(...)]
Loft(shapes, ruled=False, closed=False, guides=[], start_tangent=None, end_tangent=None, cut=False) -> Loft
# guides = RAILS the loft surface passes through (start on the first outline, end on the last; parallel, star-shaped sections)
Enclose([surface, ...]) -> Enclose   # the solid that crossing/overhanging surfaces close off; overhangs trimmed
SheetMetalCornerBreak(body, [corner_point, ...], radius, break_type=CornerBreakType.FILLET)  # round/bevel sheet corners through the thickness; points on a flange face at outline corners; flat pattern follows
SheetMetalFormTool(body, tool_solid, face_plane)  # press any solid into the sheet as a hollow form (Unfold keeps the plain sheet); don't add the tool
Sweep(profile, path, twist=0.0, frenet=True, cut=False) -> Sweep    # path: Helix3D | Spline3D
Thread(profile, pitch, height, radius, center=Point3D(0, 0, 0), dir=Point3D(0, 0, 1), lefthand=False) -> Thread
Helix3D(pitch, height, radius, center, dir, lefthand=False) -> Helix3D
Spline3D([Point3D, ...], start_tangent=None, end_tangent=None) -> Spline3D
CompositeCurve(curves) / IntersectionCurve(first, second) / ProjectedCurve(curve, plane, direction=None) -> Path3D
IsoparametricCurve(surface, direction=IsoDirection.U, at=0.5, face_finder=None) -> Path3D  # also Sweep paths / Loft guides
ProjectedEdges(sketch, body, edge_finder=None) -> profile   # sketch "Use": body edges projected into the sketch
mirror(shape, line) -> same shape type   # sketch mirror across a sketch Line (arcs, splines, custom shapes, polygons; ellipses across x/y lines)
# Surfaces (sheets): Thicken(surface, t) makes a solid, Stitch(surfaces) welds them (closed -> solid)
FillSurface(curves=[], support=None, edge_finder=None, continuity=SurfaceContinuity.G0, points=[]) -> FillSurface  # N-sided patch, one closed loop; G1 = tangent to support
BoundarySurface(curves) -> BoundarySurface   # 3-4 curves in a loop = patch; 2 separate curves = span between them
OffsetSurface(surface, distance) / ExtendSurface(surface, distance)   # move along normal / grow past free edges

solid is an un-added op (Extrusion, Lathe, Loft, another modifier…); add only the modifier.

# Shell: open-top tub 40×30×20, 2 mm walls (z 0..20)
body = Extrusion([Rectangle.from_center_and_sides(Sketch(self.xy()).origin, 40, 30)], 20)
self.add_operation(Shell(body, 2))   # open the bottom instead: face_finder=FaceFinder(InPlaneFinderRule(plane=self.xy()))
 
# Fillet: round the 4 vertical edges
body = Extrusion([Rectangle.from_center_and_sides(Sketch(self.xy()).origin, 40, 30)], 20)
self.add_operation(Fillet(body, 5, edge_finder=EdgeFinder(ParallelToAxisRule("Z"))))
 
# Edge fillet on the whole part: flange + boss, round every horizontal (X/Y) edge; vertical edges stay sharp
sk = Sketch(self.xy())
self.extrude(Rectangle.from_center_and_sides(sk.origin, 40, 30), 5)
self.add_operation(Extrusion([Rectangle.from_center_and_sides(sk.origin, 16, 12)], 20, 5))
self.fillet_edges(1, edges=EdgeFinder(EitherFinderRule([ParallelToAxisRule("X"), ParallelToAxisRule("Y")])))
 
# Chamfer: 1 mm on every edge
body = Extrusion([Rectangle.from_center_and_sides(Sketch(self.xy()).origin, 40, 30)], 20)
self.add_operation(Chamfer(body, 1))
 
# Loft: 20 mm square at z=0 to Ø10 circle at z=30
bottom, top = Sketch(self.xy()), Sketch(self.xy().get_parallel_plane(30))
self.add_operation(Loft([Rectangle.from_center_and_sides(bottom.origin, 20, 20), Circle(top.origin, 5)]))
 
# Sweep: Ø2 rod along a 3D spline (profile is moved to the path start; draw it at its sketch origin)
path = Spline3D([Point3D(0, 0, 0), Point3D(0, 10, 20), Point3D(0, 30, 30)])
self.add_operation(Sweep(Circle(Sketch(self.xy()).origin, 2), path))
 
# Thread: M10-ish external thread, z 0..15, on a Ø10 rod
self.add_operation(Extrusion([Circle(Sketch(self.xy()).origin, 5)], 20))
t = Sketch(self.xz())   # u = radial offset from `radius`, v = axial (Z)
self.add_operation(Thread(Triangle(Point(t, -0.2, -0.6), Point(t, 0.8, 0), Point(t, -0.2, 0.6)), 1.5, 15, 5))

A spring is Sweep(Circle(Sketch(self.xz()).origin, 1), Helix3D(5, 20, 10, Point3D(0, 0, 0), Point3D(0, 0, 1))).

3D primitives

center is a Point(sketch, x, y) on a sketch plane — never a bare number.

Sphere(center, radius, cut=False) -> Sphere         # centred on center
Box(center, w, d, h, cut=False) -> Extrusion       # w along sketch u, d along v, h centred on the plane (±h/2); on xy(): X, Y, Z
Cylinder(center, radius, height, cut=False, centered=False) -> Extrusion  # base on the plane, grows along the normal; centered=True → ±height/2
Cone(center, r1, r2, height) -> Extrusion          # r1 at −height/2, r2 at +height/2
Torus(center, major_radius, minor_radius) -> Lathe # axis = sketch v-axis through center (xz()/yz() → axis Z)
Wedge(center, dx, dy, dz, ltx) -> Wedge

All primitives require a Point(sketch, x, y) as center — never pass bare numbers. Create the sketch from a part plane first:

# Minimal cube: 10×10×10 mm centred at origin
class Cube(Part):
    def __init__(self):
        super().__init__()
        sketch = Sketch(self.xy())
        center = Point(sketch, 0, 0)
        self.add_operation(Box(center, 10, 10, 10))

2D shapes

RegularPolygon(center, n_sides, radius) -> Polygon
RectangleRounded(center, w, h, radius) -> CustomClosedShape
Trapezoid(center, w_top, w_bottom, h) -> Polygon
Triangle(p1, p2, p3) -> Polygon
SlotCenterToCenter(p1, p2, height) -> CustomClosedShape
SlotOverall(center, width, height) -> SlotCenterToCenter
SlotCenterPoint(center, point, height) -> SlotCenterToCenter
ConvexHull(points) -> Polygon
Text(sketch, text, size, font_url=None, xshift=0.0, yshift=0.0) -> Text  # font_url=None → Roboto; Extrusion([Text(...)], 2)

Hole variants

CounterBoreHole(point, radius, depth, cbore_radius, cbore_depth) -> Lathe
CounterSinkHole(point, radius, depth, csink_radius, csink_angle_deg) -> Lathe
TappedHole(point, thread_size, depth) -> Hole          # bore at radius = thread_size/2

Solid transforms

Mirror(shape, plane_name) -> Mirror             # plane_name in {"XY", "YZ", "XZ"}
Scale(shape, factor) -> Scale                   # uniform
Offset2D(shape, distance) -> Offset2D
BoundingBox(shape) -> BoundingBox
Section(solid, plane_name) -> Section
Split(solid, plane_name, keep) -> Split
LinearPattern(shape, direction, count, spacing, direction2=None, count2=1, spacing2=0.0) -> LinearPattern  # direction2 → count × count2 grid
PolarPattern(shape, count, angle=360.0, axis_origin=Point3D(0, 0, 0), axis_direction=Point3D(0, 0, 1)) -> PolarPattern
CurvePattern(shape, path, count, align_to_path=False) -> CurvePattern  # path: Spline3D | Helix3D, evenly by arc length; seed drawn at the path start
# Shortcuts self.linear_pattern / polar_pattern / curve_pattern add the op; shape=None repeats the part's body so far
MoveBody(shape, translation, rotation_angle=0.0, rotation_axis=Point3D(0, 0, 1), rotation_origin=Point3D(0, 0, 0)) -> MoveBody
self.delete_bodies(bodies) -> DeleteBodies       # multi-body part: drop every body sharing volume with these ops (one op or a list)
self.keep_bodies(bodies) -> KeepBodies           # the inverse: keep only those bodies; later ops apply on top
Project(shape, target_plane_name) -> Project
Draft(solid, angle_deg, neutral_plane_name, edge_finder) -> Draft
PartingLineDraft(solid, angle_deg, parting_plane=None, parting_edges=None, face_finder=None, both_sides=True) -> PartingLineDraft  # walls keep their outline on the parting plane / planar edge chain, taper away on both sides
OffsetFace(solid, face_finder, distance) -> OffsetFace   # push/pull faces along their normal (+ grows)
MoveFace(solid, face_finder, translation=Point3D(0, 0, 0), rotation_angle=0, rotation_axis=Point3D(0, 0, 1), rotation_origin=Point3D(0, 0, 0)) -> MoveFace  # planar face to a new plane; side walls extend (prismatic regions only)
DeleteFace(solid, face_finder) -> DeleteFace   # delete a hole / pocket / slot / boss's faces and heal (planar boundary loops only)
FullRound(solid, face_finder) -> FullRound
Trace(path_points, width) -> Trace

Pattern helpers

GridLocations(center, x_pitch, y_pitch, n_x, n_y).positions() -> list[Point]
hole_pattern(GridLocations(...) | Locations(...) | [Point], radius, depth) -> ONE op (grid: LinearPattern; list: one multi-circle cut)
ring(center, outer_r, inner_r, depth, cut=False) -> Extrusion  # annulus / groove in one op (thin_wall)
HexLocations(center, pitch, n_radial).positions() -> list[Point]
PolarLocations(center, radius, count, start_angle_deg=0, angular_range_deg=360).positions() -> list[Point]
Locations(center, [(dx, dy), ...]).positions() -> list[Point]

1D curves

Polyline([points]) -> CustomOpenShape
FilletPolyline([points], radius) -> CustomOpenShape
Bezier([start, ctrl1, ..., end]) -> Bezier
BSpline([points], degree=3) -> BSpline
ThreePointArc(p1, p2, p3) -> Arc
RadiusArc(p1, p3, radius) -> Arc
CenterArc(center, radius, start_angle_deg, end_angle_deg) -> Arc
SagittaArc(p1, p3, sagitta) -> Arc
TangentArc(p1, p3, tangent) -> Arc
JernArc(start, tangent, radius, arc_size_deg) -> Arc
EllipticalCenterArc(center, x_radius, y_radius, start_angle_deg, end_angle_deg) -> EllipseArc
Helix2D(center, pitch, radius_outer, n_turns) -> Spline
Spline(points, start_tangent=None, end_tangent=None) -> Spline

Selectors

Extend EdgeFinder.rule with these to filter edges/faces:

IsCircleRule()
OfTypeRule(type_name)                          # "LINE" | "CIRCLE" | "BSPLINE" | "ELLIPSE"
LengthRangeRule(min, max)
RadiusRangeRule(min, max)
ParallelToAxisRule(axis)                       # "X" | "Y" | "Z"
OnFaceRule(face_finder)
SortByRule(rule, by, take="FIRST", n=1)        # by: LENGTH|RADIUS|AREA|VOLUME|DISTANCE

Transforms

(Part | Assembly).translate([x, y, z]) -> bool | None
(Part | Assembly).translate_x(x) -> bool | None
(Part | Assembly).translate_y(y) -> bool | None
(Part | Assembly).translate_z(z) -> bool | None
(Part | Assembly).rotate(angle, axis=[0.0, 0.0, 1.0]) -> bool | None

Materials

material = Material()
material.set_diffuse_color("red")  # or [r, g, b]
part.set_material(material)
part.paint("blue", transparency=0.5)

TFHelper

tf = TFHelper()
tf.get_tf() -> dict
tf.set_tf(value)
tf.translate([x, y, z])
tf.translate_x(x)
tf.translate_y(y)
tf.translate_z(z)
tf.rotate(axis, angle)

Recipes

# Open box 60×40×30, 2 mm walls, separate lid that rests on the rim with a locating lip
L, W, H, T, LIP, GAP = 60, 40, 30, 2, 3, 0.2
 
class Tub(Part):
    def __init__(self):
        super().__init__()
        body = Extrusion([Rectangle.from_center_and_sides(Sketch(self.xy()).origin, L, W)], H)  # z 0..30
        self.add_operation(Shell(body, T))  # top face removed → open tub
 
class Lid(Part):
    def __init__(self):
        super().__init__()
        s = Sketch(self.xy())
        self.add_operation(Extrusion([Rectangle.from_center_and_sides(s.origin, L, W)], H + T, start=H))  # z 30..32
        lip = Rectangle.from_center_and_sides(s.origin, L - 2 * (T + GAP), W - 2 * (T + GAP))
        self.add_operation(Extrusion([lip], H, start=H - LIP))  # z 27..30, keys inside the walls
 
class Enclosure(Assembly):
    def __init__(self):
        super().__init__()
        self.add_component(Tub())
        self.add_component(Lid())   # already at its seated height; lid.translate_z(15) to explode
# Ring (ID 20, OD 28, 4 wide) whose axis is world X: revolve a section about a sketch line along X
class RingAboutX(Part):
    def __init__(self):
        super().__init__()
        s = Sketch(self.xy())  # u = X, v = Y
        x_axis = Axis(Line(Point(s, 0, 0), Point(s, 1, 0)))
        self.add_operation(Lathe(Rectangle.from_center_and_sides(Point(s, 0, 12), 4, 4), x_axis))
# Axis Z instead: sketch on xz(), axis Line(Point(s, 0, 0), Point(s, 0, 1)), section at Point(s, 12, 0).

Good practice

  • For reusable parts, define subclasses of Part and split build logic into methods.
  • For reusable assemblies, define subclasses of Assembly and compose children explicitly.