API Reference¶
This reference is generated from ldraw.__all__ at build time, then rendered
from the exported objects' type annotations and docstrings with mkdocstrings.
Generated ldraw.library.* modules are intentionally not included because they
depend on the locally downloaded LDraw release. Run ldraw generate and
ldraw stubs in consuming projects for release-specific import and type-stub
coverage.
BomRow
dataclass
¶
One line of a bill of materials.
to_dict
¶
Return the row as a plain dict keyed by BOM_FIELDS.
BoundingBox
dataclass
¶
An axis-aligned box in LDraw units (LDU).
LDraw's Y axis points down, so min.y is the highest point of the
part (typically the stud tops) and max.y the lowest.
CatalogEntry
dataclass
¶
Colour
dataclass
¶
A colour, identified by a code, or by rgb/alpha for direct colours.
rgb is canonicalized on construction to #RRGGBB — a leading
#, six uppercase hex digits — whatever form it was given in;
malformed values raise ValueError.
is_solid
property
¶
Whether this colour is plain opaque paint — no alpha, no finish.
Judged from the data on this instance: full alpha (or none given)
and no colour attributes (CHROME, GLITTER, LUMINANCE,
…). Colours from a parts catalog carry both fields; a bare
Colour(code=...) placeholder carries neither and so reads as
solid — look the code up in Parts.colours_by_code to judge the
real palette entry.
swatch_rgb
property
¶
RGB hex value suitable for colour swatches, when known.
LDrawPaths
dataclass
¶
Resolved filesystem paths for one pyldraw configuration.
LDrawSession
¶
LDrawState
dataclass
¶
Freshness state for a configured LDraw library and generated data.
LDrawStateReason
¶
Matrix
dataclass
¶
A 3x3 transformation matrix.
Model
dataclass
¶
A whole LDraw model, optionally with MPD submodels.
Models compare and hash by identity: their objects contain
identity-compared pieces, so field-wise equality would be meaningless.
Compare model content with m1.to_ldraw() == m2.to_ldraw().
objects
class-attribute
instance-attribute
¶
submodels
class-attribute
instance-attribute
¶
description
property
¶
The description from the first line, when it is an unmanaged comment.
steps
property
¶
Pieces grouped by 0 STEP markers.
Pieces after the last marker form a final step, so a model without
any 0 STEP lines is a single step. A trailing marker does not
produce an empty step. Submodel references are not expanded.
submodel_for
¶
Resolve a piece's subfile reference to a submodel, if any.
source_line_for
¶
Return the parsed source line for this exact piece object.
add
¶
Append parsed objects (pieces, comments, geometry) to the model.
add_group
¶
Append a group's pieces; group transforms apply at serialization.
from_pieces
classmethod
¶
from_pieces(
pieces: Iterable[Piece],
*,
name: str = "",
description: str | None = None,
author: str | None = None,
) -> Self
Build a model from pieces, optionally with header comments.
set_header
¶
set_header(
*,
description: str | None = None,
name: str | None = None,
author: str | None = None,
ldraw_org: str | None = None,
license: str | None = None,
) -> None
Set or replace standard header lines at the top of the model.
ldraw_org and license write the 0 !LDRAW_ORG and
0 !LICENSE meta commands, placed after any Name:/Author:
comments in canonical header order.
add_submodel
¶
add_submodel(
submodel: Model,
*,
colour: Colour | int = MAIN_COLOUR_CODE,
position: Vector | None = None,
matrix: Matrix | None = None,
) -> Piece
Register a submodel and append a type-1 piece referencing it.
The submodel's own nested submodels are hoisted into this model's
flat mapping, since serialization only walks one level. The same
submodel object may be added repeatedly; each call appends another
placement piece. A different model under an already-registered
name still raises DuplicateSubmodelError.
submodel_view
¶
Return a submodel that resolves references against this root.
Models taken straight from Model.submodels have an empty
submodel table, so iterating them treats references to sibling
submodels as leaf pieces. The returned model shares this root's
submodel table instead, making iter_pieces,
bill_of_materials, and find_pieces(recursive=True) expand
nested references correctly. It is a live view — its objects and
submodel table are shared with this model, not copied.
Raises UnknownSubmodelError for a name that is neither this
model's nor one of its submodels'.
iter_pieces
¶
Recursively yield leaf pieces, expanding submodel references.
References are resolved against this model's submodel table. A
model taken straight from Model.submodels has an empty table,
so references to sibling submodels are silently yielded as if they
were leaf pieces — inspect a submodel through
root.submodel_view(name) instead.
iter_occurrences
¶
iter_occurrences(
*,
expand_submodels: bool = True,
include_steps: bool = True,
) -> Iterator[ModelOccurrence]
Yield placed part occurrences with transform and source context.
bill_of_materials
¶
Count leaf pieces by part and colour, expanding submodel references.
Colour 16 (the main colour) inside a submodel is resolved to the
colour the submodel was placed with. As with iter_pieces,
submodel references only resolve against this model's own submodel
table; to count a single submodel of a larger model, call this on
root.submodel_view(name).
find_pieces
¶
find_pieces(
*,
part: str | None = None,
colour: Colour | int | None = None,
recursive: bool = False,
) -> list[Piece]
Return pieces matching the given part code and/or colour.
Part codes are compared case-insensitively.
ModelOccurrence
dataclass
¶
One placed leaf part occurrence in a model.
Occurrences are traversal events: two placements of the same submodel produce distinct occurrences, so they compare and hash by identity.
ModelSummary
dataclass
¶
Reusable summary of a model's placed parts and geometry extents.
from_model
classmethod
¶
Build a summary for model using geometry from parts.
PartCategory
¶
Bases: StrEnum
Known LDraw part categories, mirroring the official LDraw.org list.
CONSTRACTION_ACCESSORY
class-attribute
instance-attribute
¶
module_name
property
¶
Return the generated module name for this category.
These names are a frozen public contract: renaming one would break
existing ldraw.library.parts.* imports.
from_label
classmethod
¶
Return the category matching an LDraw label.
PartReference
dataclass
¶
A type-1 subfile reference found inside a part file.
Parts
¶
Part catalog loader.
ColourAttributes
class-attribute
instance-attribute
¶
ColourAttributes = (
"CHROME",
"PEARLESCENT",
"RUBBER",
"MATTE_METALLIC",
"METAL",
"GLITTER",
"SPECKLE",
"LUMINANCE",
)
by_category
instance-attribute
¶
get
classmethod
¶
Get a memoized Parts instance, keyed by path, mtime, and size.
from_catalog
classmethod
¶
Construct a Parts that adopts a prebuilt catalog.
Skips the expensive per-part categorization pass.
adopt_catalog
¶
Adopt a prebuilt catalog, skipping categorization.
A no-op when this instance is already categorized, so a memoized instance can safely adopt the same persisted index repeatedly.
get_entry_by_code
¶
Return a typed catalog entry by part code.
get_entry_by_description
¶
Return a typed catalog entry by part description.
entries_by_category
¶
Return entries in a part category.
minifig_entries
¶
Return entries in minifigure sections.
get_category
¶
Get the category of a part based on its description.
load
¶
Load the parts list, colours, and primitives (all cheap passes).
The expensive categorization pass — opening every part file for its
!CATEGORY header — runs lazily on first catalog access.
section_find
¶
Return code and description from a parts.lst split line.
The description is kept exactly as written in parts.lst;
detected minifig sections are recorded for the catalog. Generated
symbol names strip the Minifig prefix at generation time
(see symbol_description).
description_for
¶
Return the parts.lst description for a part code, or None.
The lookup tolerates casing differences: Piece.part preserves
whatever casing the source used while parts.lst codes are
typically lowercase, so the code is tried as given, lowercased,
and uppercased.
part
¶
Get a Part from its description or code.
Raises PartNotFoundError when the description or code is not
in the library or the part file is missing; use find_part for
a lookup that returns None instead.
find_part
¶
Get a Part from its description or code, or None when not found.
bounding_box
¶
Axis-aligned bounding box of a part's geometry, in LDU.
Subfiles are resolved recursively; unresolvable ones are skipped
with a warning. Raises PartNotFoundError for an unknown code
and NoGeometryError when the part draws nothing.
studs
¶
All stud primitives a part places, in the part's own coordinates.
Includes underside tubes and other downward studs; filter with
StudReference.is_top_stud or use stud_positions.
stud_positions
¶
Positions of a part's top studs (upward connectors), in LDU.
resolve_colour
¶
Return catalog metadata for colour when it is known.
references_for
¶
Return type-1 references placed by a part file.
Person
¶
Representation of a LEGO minifigure.
hat
¶
Add a hat piece to the figure's head.
backpack
¶
Add a backpack.
hips_and_legs
¶
Add combined hips and legs.
left_arm
¶
Add a left arm.
left_hand
¶
Add a left hand piece to the figure's left arm.
left_hand_item
¶
left_hand_item(
left_hand: Piece,
colour: ColourInput,
displacement: Vector,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add an item to the left hand.
right_arm
¶
Add a right arm.
right_hand
¶
Add a right hand piece to the figure's right arm.
right_hand_item
¶
right_hand_item(
right_hand: Piece,
colour: ColourInput,
displacement: Vector,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a right hand item.
left_leg
¶
Add a left leg.
left_shoe
¶
left_shoe(
left_leg: Piece,
colour: ColourInput,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a shoe on the left.
right_leg
¶
Add a right leg.
right_shoe
¶
right_shoe(
right_leg: Piece,
colour: ColourInput,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a shoe on the right.
Piece
dataclass
¶
A part with a defined colour, position, and rotation.
place
classmethod
¶
place(
part: str,
*,
colour: Colour | int = MAIN_COLOUR_CODE,
position: Vector | None = None,
matrix: Matrix | None = None,
group: Group | None = None,
suffix: str = DEFAULT_SUFFIX,
) -> Self
Create a piece keyword-first, defaulting to the origin and identity.
ProgressEvent
dataclass
¶
One progress update from a long-running library operation.
Severity
¶
SkippedGeometry
dataclass
¶
StudReference
dataclass
¶
A stud primitive placed by a part, in the part's own coordinates.
description
instance-attribute
¶
The primitive's header description, e.g. Stud Tube Open.
position
instance-attribute
¶
The primitive's origin -- for top studs, the centre of the stud base.
up
class-attribute
instance-attribute
¶
Image of the stud's local up direction (0, -1, 0) under the placing transforms; unit length under rigid placements.
is_top_stud
property
¶
Whether this stud is an upward connector a brick can sit on.
Excludes underside tubes and placeholder primitives by description, and any stud whose placing transforms point it away from up (LDraw up is -Y), such as the sideways front stud of a headlight brick.
ValidationIssue
dataclass
¶
Vector
dataclass
¶
A vector in 3D.
XAxis
¶
Bases: Axis
X-axis representation.
YAxis
¶
Bases: Axis
Y-axis representation.
ZAxis
¶
Bases: Axis
Z-axis representation.
bill_of_materials
¶
Count leaf pieces by part and colour, expanding submodel references.
A submodel placed twice contributes its pieces twice. Submodel reference pieces themselves are expanded, never counted. Colour 16 (the main colour) inside a submodel is resolved to the colour the submodel was placed with. Descriptions and colour names are resolved when a parts catalog is given.
References only resolve against the given model's own submodel table.
To count one submodel of a larger model, pass
root.submodel_view(name) rather than a model taken straight from
Model.submodels — the latter treats nested submodel references as
leaf parts.
Part codes are counted case-insensitively; each row shows the code as first written in the model.
download
¶
download(
*,
show_progress: bool = True,
version: str = COMPLETE_VERSION,
on_progress: ProgressCallback | None = None,
) -> str
Download and unpack an LDraw library version, generating parts.lst file.
The complete library comes from ldraw.org; versioned releases come from snapshot tags of the rienafairefr/ldraw-parts GitHub repository.
ensure_library
¶
ensure_library(
config: Config | None = None,
*,
version: str = COMPLETE_VERSION,
write_config: bool = False,
config_file: str | Path | None = None,
force_generate: bool = False,
on_progress: ProgressCallback | None = None,
) -> LDrawSession
Ensure a configured library, generated package, and catalog index exist.
When the library is downloaded, config.ldraw_library_path is
updated in place on the caller's Config (persisted only when
write_config is true), and the process-global default import
configuration is replaced via LibraryImporter.set_config.
generate
¶
generate(
config: Config,
*,
force: bool = False,
on_progress: ProgressCallback | None = None,
) -> None
Generate the library from configuration.
iter_ldr_issues
¶
Yield the issues found in an LDraw model or part file.
Malformed lines, unparseable colour values, and (when a parts catalog with colour definitions is given) unknown part references and colour codes are errors. Suspicious-but-legal constructs — legacy dithered colours, non-orthonormal or singular transformation matrices, and unknown bang meta-commands — are warnings.
model_bounds
¶
Return the true transformed bounds for model in LDraw units.
parse_model
¶
Parse LDraw document text into a Model.
A document without 0 FILE sections becomes a single model. In an MPD
document the first section becomes the returned root model and later
sections become its submodels, resolvable via Model.submodel_for.
rows_to_csv
¶
Serialize rows to CSV text with a header line.
rows_to_json
¶
Serialize rows to a JSON array of objects.
Config
¶
Configuration settings for pyldraw.
ldraw_library_path
instance-attribute
¶
ldraw_library_path: str = (
ldraw_library_path
if ldraw_library_path is not None
else str(Path(get_cache_dir()) / "complete")
)
generated_path
instance-attribute
¶
generated_path: str = (
generated_path
if generated_path is not None
else str(Path(get_data_dir()) / "generated")
)
load
classmethod
¶
Load configuration from YAML file or create default configuration.
A missing file yields the defaults; an unreadable or malformed
file raises ConfigLoadError naming the path and the problem.
write
¶
Write the config atomically with a unique sibling temporary file.
NoGeometryError
¶
Bases: PartError
The part (including its subfiles) draws no geometry at all.
add_context
¶
Extend the message with file/line context, at most once.
PartNotFoundError
¶
Bases: PartError
Part was not found as expected.
add_context
¶
Extend the message with file/line context, at most once.
UnknownSubmodelError
¶
Bases: PartError
The requested submodel name is not in this model's submodel table.
part_bounding_box
¶
Axis-aligned bounding box of a part's geometry, in LDU.
Subfiles are resolved recursively and their memoized boxes composed by transforming box corners, which is exact under the axis-aligned rotations that dominate the library and slightly conservative under oblique ones. Unresolvable subfiles are skipped with a warning.
Raises PartNotFoundError for an unknown code and
NoGeometryError when the part draws nothing.
part_studs
¶
All stud primitives a part places, in the part's own coordinates.
Stud groups and subparts are expanded down to individual stud*
primitives; recursion stops at each stud so nothing is counted twice.
Filter with StudReference.is_top_stud (or use
Parts.stud_positions) to keep only upward connectors.
symbol_description
¶
Return the description that generated symbol names derive from.
Minifig part descriptions drop their Minifig prefix so symbols in
the minifig/minifig_* modules read Torso, not
MinifigTorso; every other description passes through unchanged.
module_path
¶
Return the generated module path containing entry, if any.
suggested_import
¶
Return an import statement for entry in the generated library.
symbol_name
¶
Return the generated Python symbol name for a catalog entry.
symbol_name_for_description
¶
Return the generated Python symbol for an LDraw description.