kicad monkey v2026.11.30
On This Page (38)

S-Expression & Foundation

S-expression parser/writer, span iterators, object collections, and utility helpers.

38 public symbols.

EmbeddedFileDecoder

class
from kicad_monkey import EmbeddedFileDecoder
class EmbeddedFileDecoder() -> 'None'

Decode embedded files, decoding and checking each distinct one once.

``decode`` returns and raises what :func:`decode_embedded_file` does. A
file is known by its name, data presence, checksum and encoded data, so
the copies of one model that KiCad embeds in every footprint using it are
decoded and checked once and share one bytes object. A copy that differs
in any of these, such as the same data under another checksum, is decoded
and checked on its own. A decoder keeps what it decoded while it lives.

Members (1)
MemberKindSignatureSummary
decodemethod(self, file: 'EmbeddedFile') -> 'bytes | None'Return ``decode_embedded_file(file)``, decoded once per distinct file.

FootprintPadSizeNormalization

class
from kicad_monkey import FootprintPadSizeNormalization
class FootprintPadSizeNormalization(expression: 'Any', changes: 'tuple[PadSizeNormalizationChange, ...]') -> 'None'

The mutated expression and structured direct-pad repair diagnostics.

Members (1)
MemberKindSignatureSummary
countproperty -> 'int'Return the number of direct pad sizes that were repaired.

KiCadEnvironment

class
from kicad_monkey import KiCadEnvironment
class KiCadEnvironment(*, env: 'Mapping[str, str] | None' = None, platform: 'str | None' = None) -> 'None'

Discover local KiCad installations and user configuration directories.

Members (8)
MemberKindSignatureSummary
config_path_variablesmethod(self, *, version: 'tuple[int, int] | None' = None) -> 'dict[str, str]'Return user ``environment.vars`` overrides from ``kicad_common.json``.
extra_3d_model_search_dirsmethod(self, *, version: 'tuple[int, int] | None' = None) -> 'tuple[Path, ...]'Return ``system.extra_3d_search_dirs`` from ``kicad_common.json``.
fallback_model_dirmethod(self) -> 'Path | None'Return the highest KiCad installation's 3D models directory, preferring non-beta.
find_config_pathsmethod(self, *, min_major: 'int | None' = None) -> 'list[Path]'Return KiCad user configuration version directories sorted by version.
find_installationsmethod(self) -> 'list[KiCadInstallation]'Return detected KiCad installations sorted by filesystem path.
highest_installationmethod(self, installations: 'Sequence[KiCadInstallation | str | Path] | None' = None, *, ignore_beta: 'bool' = True) -> 'KiCadInstallation | None'Return the highest versioned KiCad installation, optionally skipping .99 beta builds.
model_directory_variablesmethod(self) -> 'dict[str, str]'Return KiCad's implicit ``KICAD<major>_3DMODEL_DIR`` path variables.
path_variable_mapmethod(self, *, version: 'tuple[int, int] | None' = None) -> 'dict[str, str]'Return install model-dir variables overlaid with user config overrides.

KiCadFilterPipeline

class
from kicad_monkey import KiCadFilterPipeline
class KiCadFilterPipeline()

File-level KiCad cleanup transforms for generated or migrated artifacts.

Members (5)
MemberKindSignatureSummary
filter_footprintmethod(self, path_in: 'str | Path', out_path: 'str | Path') -> 'None'Apply all footprint filters, including generated Fab geometry.
filter_footprint_importmethod(self, path_in: 'str | Path', out_path: 'str | Path') -> 'None'Clean an imported footprint without synthesizing Fab geometry.
filter_pcbmethod(self, path_in: 'str | Path', out_path: 'str | Path', *, reset_layer_names: 'bool' = False) -> 'None'Apply PCB filters to a `.kicad_pcb` file.
filter_schematicmethod(self, path_in: 'str | Path', out_path: 'str | Path') -> 'None'Apply all schematic filters to a `.kicad_sch` file.
filter_symbolmethod(self, path_in: 'str | Path', out_path: 'str | Path') -> 'None'Apply all symbol filters to a `.kicad_sym` file.

KiCadModelResolution

class
from kicad_monkey import KiCadModelResolution
class KiCadModelResolution(authored_locator: 'str', status: 'KiCadModelResolutionStatus', resolved_name: 'str | None' = None, payload: 'bytes | None' = None, via_sibling: 'bool' = False, standard_library_reference: 'bool' = False) -> 'None'

Bounded model payload outcome without exposing an absolute host path.

Members (1)
MemberKindSignatureSummary
resolvedproperty -> 'bool'Return whether a nonempty bounded payload was resolved.

KiCadModelResolver

class
from kicad_monkey import KiCadModelResolver
class KiCadModelResolver(env: 'dict[str, str] | None' = None, *, model_search_dirs: 'Sequence[Path] | None' = None, use_installed_kicad: 'bool' = True, resolve_wrl_siblings: 'bool' = True) -> 'None'

Resolve repeated KiCad model locators with one environment snapshot.

KiCad Monkey owns variable precedence, configured search directories, and
WRL-to-STEP sibling selection. The public result carries the authored
locator and bounded bytes but deliberately omits the resolved absolute
path so downstream packages do not persist host identity.

Members (3)
MemberKindSignatureSummary
contextmethod(self) -> 'KiCadModelSearchContext'Return a copied host snapshot, never a canonical model/report field.
from_contextclassmethod(cls, context: 'KiCadModelSearchContext') -> 'KiCadModelResolver'Use an explicit snapshot; do not discover or reread host configuration.
resolvemethod(self, authored_locator: 'str', *, project_root: 'Path | str | None', max_bytes: 'int' = 67108864) -> 'KiCadModelResolution'Return one bounded payload or an explicit unresolved outcome.

KiCadModelSearchContext

class
from kicad_monkey import KiCadModelSearchContext
class KiCadModelSearchContext(variables: 'dict[str, str]' = <factory>, fallback_model_dir: 'Path | None' = None, search_dirs: 'tuple[Path, ...]' = (), resolve_wrl_siblings: 'bool' = True, max_search_entries: 'int' = 20000) -> 'None'

Resolution inputs for KiCad 3D model references.

``variables`` maps path-variable names to directories. ``fallback_model_dir``
is the highest installed KiCad ``3dmodels`` directory, used when a
``KICAD<major>_3DMODEL_DIR`` reference names a version that is not installed.
``search_dirs`` are explicit override roots tried (by the path tail) for any
leading-variable reference. ``resolve_wrl_siblings`` lets a ``.wrl`` reference
fall back to its sibling ``.step``/``.stp`` model.

KiCadNameIndex

class
from kicad_monkey import KiCadNameIndex
class KiCadNameIndex()

Fast symbol and footprint name extraction for KiCad library files.

Members (6)
MemberKindSignatureSummary
build_footprint_indexmethod(self, starting_path: 'Path | str') -> 'dict[str, list[Path]]'Build a footprint-name -> files index for a directory tree.
build_symbol_indexmethod(self, starting_path: 'Path | str') -> 'dict[str, list[Path]]'Build a symbol-name -> files index for a directory tree.
find_footprintsmethod(self, footprint_name: 'str', starting_path: 'Path | str', *, fuzzy: 'bool' = False) -> 'list[dict[str, Path | str]]'Find footprint files that declare the requested footprint name or library folder.
find_symbolsmethod(self, symbol_name: 'str', starting_path: 'Path | str', *, fuzzy: 'bool' = False) -> 'list[dict[str, Path | str]]'Find symbol files that declare the requested symbol name.
footprint_namesmethod(self, filename: 'Path | str') -> 'list[str]'Extract the declared footprint name from a `.kicad_mod` file.
symbol_namesmethod(self, filename: 'Path | str') -> 'list[str]'Extract top-level symbol names from a `.kicad_sym` file.

KiCadObjectCollection

class
from kicad_monkey import KiCadObjectCollection
class KiCadObjectCollection(provider: 'Callable[[], Iterable[T]]', *, owner: 'object | None' = None) -> 'None'

Read-only live view over a model-owned object collection.

Members (13)
MemberKindSignatureSummary
appendmethod(self, *args, **kwargs) -> 'None'
clearmethod(self, *args, **kwargs) -> 'None'
countmethod(self, value: 'object' = <object object at 0x74f655d83870>, **attrs) -> 'int'Count items matching an optional type/name and exact attributes.
extendmethod(self, *args, **kwargs) -> 'None'
firstmethod(self, kind: 'KindFilter' = None, **attrs) -> 'T | None'Return the first matching item, or None.
insertmethod(self, *args, **kwargs) -> 'None'
of_typemethod(self, kind: 'type | tuple[type, ...] | str') -> "'KiCadObjectCollection[T]'"Return a live view filtered by class or class name.
popmethod(self, *args, **kwargs) -> 'None'
removemethod(self, *args, **kwargs) -> 'None'
reversemethod(self, *args, **kwargs) -> 'None'
sortmethod(self, *args, **kwargs) -> 'None'
to_listmethod(self) -> 'list[T]'Materialize the current view as a list.
wheremethod(self, kind: 'KindFilter' = None, **attrs) -> "'KiCadObjectCollection[T]'"Return a live view filtered by type/name and exact attributes.

PadSizeNormalizationChange

class
from kicad_monkey import PadSizeNormalizationChange
class PadSizeNormalizationChange(pad_name: 'str', original_size: 'tuple[float, float]', replacement_size: 'tuple[float, float]' = (0.001, 0.001)) -> 'None'

One direct pad-size repair made by KiCad-compatible normalization.

SexpFormSpan

class
from kicad_monkey import SexpFormSpan
class SexpFormSpan(head: 'str | None', path: 'tuple[str, ...]', depth: 'int', start_offset: 'int', end_offset: 'int', line: 'int', column: 'int', end_line: 'int', end_column: 'int', source_text: 'str | None' = None, source_path: 'str | None' = None) -> 'None'

Source span for one complete selected S-expression form.

Members (2)
MemberKindSignatureSummary
parsemethod(self) -> 'Any'Parse this selected form into the normal nested-list representation.
textmethod(self) -> 'str'Return the exact source text for this form.

SexpSelector

class
from kicad_monkey import SexpSelector
class SexpSelector(heads: 'frozenset[str] | Iterable[str] | str | None' = None, paths: 'frozenset[tuple[str, ...]] | Iterable[Iterable[str]] | None' = None, min_depth: 'int | None' = None, max_depth: 'int | None' = None, prune_heads: 'frozenset[str] | Iterable[str] | str' = frozenset()) -> 'None'

Read-only selector for projection scanning S-expression forms.

Members (2)
MemberKindSignatureSummary
matchesmethod(self, span: "'SexpFormSpan'") -> 'bool'Return whether ``span`` matches this selector.
should_scan_childrenmethod(self, *, head: 'str | None', path: 'tuple[str, ...]', depth: 'int') -> 'bool'Return whether nested forms below this form can match.

Version

class
from kicad_monkey import Version
class Version(major: 'int', minor: 'int', patch: 'int', string: 'str', build: 'int | None' = None, alpha: 'int | None' = None) -> 'None'

Parsed package version using the project date-version contract.

Members (2)
MemberKindSignatureSummary
is_prereleaseproperty -> 'bool'Return True for alpha release-candidate builds.
release_dateproperty -> 'date'Return the calendar release date encoded by the version.

build_sexp

function
from kicad_monkey import build_sexp
def build_sexp(exp: 'Any', indent: 'str' = '') -> 'str'

Build s-expression string from parsed data. Uses list-based building for O(n) performance.

decode_embedded_file

function
from kicad_monkey import decode_embedded_file
def decode_embedded_file(file: 'EmbeddedFile') -> 'bytes | None'

Read existing source bytes; absent differs from explicitly empty data.

Every nonempty encoded stream requires its authored SHA-256 or seeded
MMH3 checksum. Complete concatenated zstd frames are supported. Source
records remain unchanged; malformed data raises ValueError. KiCad decodes
embedded files without size ceilings, and so does KiCad Monkey.

embedded_file_decoder

function
from kicad_monkey import embedded_file_decoder
def embedded_file_decoder(owner: 'object') -> 'EmbeddedFileDecoder'

Return the decoder kept for one board (or other owner) while it lives.

Every caller reading that board's embedded files shares it, so a command
decodes and checks each distinct payload once across all its views and
sides. The owner itself is not changed.

extract_footprints_from_text

function
from kicad_monkey import extract_footprints_from_text
def extract_footprints_from_text(pcb_text: 'str') -> 'list[KiCadFootprint]'

Extract standalone footprint objects from PCB file text.

Args:
pcb_text: Contents of a .kicad_pcb file

Returns:
List of KiCadFootprint objects ready to write as .kicad_mod files

extract_step_from_text

function
from kicad_monkey import extract_step_from_text
def extract_step_from_text(footprint_text: 'str') -> 'tuple[str, bytes] | None'

Extract STEP model data from footprint file text.

Args:
footprint_text: Contents of a .kicad_mod file

Returns:
Tuple of (filename, step_data_bytes) if found, else None

extract_symbols_from_text

function
from kicad_monkey import extract_symbols_from_text
def extract_symbols_from_text(schematic_text: 'str') -> 'list[LibSymbol]'

Extract library symbol objects from schematic file text.

Args:
schematic_text: Contents of a .kicad_sch file

Returns:
List of LibSymbol objects ready to write into .kicad_sym files

find_all_elements

function
from kicad_monkey import find_all_elements
def find_all_elements(sexp: 'list', name: 'str') -> 'List[list]'

Find all sub-elements by name.

find_element

function
from kicad_monkey import find_element
def find_element(sexp: 'list', name: 'str') -> 'Optional[list]'

Find first sub-element by name.

format_sexp

function
from kicad_monkey import format_sexp
def format_sexp(sexp: 'str', indentation_size: 'int' = 2, max_nesting: 'int' = 2) -> 'str'

Format an S-expression string using the KiCad lexer for tokenization.

get_value

function
from kicad_monkey import get_value
def get_value(sexp: 'list', name: 'str', default: 'Any' = None) -> 'Any'

Get value of named element (first value after the name).

get_values

function
from kicad_monkey import get_values
def get_values(sexp: 'list', name: 'str') -> 'List[Any]'

Get all values of named element (all values after the name).

iter_kicad_objects_from_file

function
from kicad_monkey import iter_kicad_objects_from_file
def iter_kicad_objects_from_file(path: 'str | Path', object_type: 'type[T]', *, selector: 'SexpSelector | None' = None, predicate: 'SexpPredicate | None' = None) -> 'Iterator[T]'

Yield typed KiCad objects from selected forms in ``path``.

iter_kicad_objects_from_text

function
from kicad_monkey import iter_kicad_objects_from_text
def iter_kicad_objects_from_text(text: 'str', object_type: 'type[T]', *, selector: 'SexpSelector | None' = None, predicate: 'SexpPredicate | None' = None, source_path: 'str | Path | None' = None) -> 'Iterator[T]'

Yield typed KiCad objects from selected forms without parsing the full file.

``object_type`` must expose ``from_sexp``. If ``selector`` is omitted, a
built-in selector is used for known KiCad OOP classes such as ``Footprint``,
``LibSymbol``, ``SchSymbol``, ``Model``, and common PCB/schematic primitives.
Pass ``selector`` when using this with a custom class or an uncommon form.

iter_sexp_file_form_spans

function
from kicad_monkey import iter_sexp_file_form_spans
def iter_sexp_file_form_spans(path: 'Path | str', selector: 'SexpSelector | None' = None) -> 'Iterator[SexpFormSpan]'

Yield selected form spans from an S-expression file.

iter_sexp_form_spans

function
from kicad_monkey import iter_sexp_form_spans
def iter_sexp_form_spans(sexp: 'str', selector: 'SexpSelector | None' = None, *, source_path: 'Any' = None) -> 'Iterator[SexpFormSpan]'

Yield selected S-expression form spans without building a full tree.

KiCadModelResolutionStatus

enum
from kicad_monkey import KiCadModelResolutionStatus
enum KiCadModelResolutionStatus

Host resolution outcome for one authored KiCad model locator.

Members (3)
MemberKindSignatureSummary
RESOLVEDmember= 'resolved'
MISSINGmember= 'missing'
VARIABLE_UNRESOLVEDmember= 'variable_unresolved'

normalize_unsafe_footprint_pad_sizes

function
from kicad_monkey import normalize_unsafe_footprint_pad_sizes
def normalize_unsafe_footprint_pad_sizes(expression: 'Any') -> 'FootprintPadSizeNormalization'

Pin unsafe direct pad sizes to 1 um, matching KiCad's native parser.

KiCad treats a pad as algorithmically unsafe when either axis in its
direct/default ``(size x y)`` form is nonpositive. It repairs that pad by
setting both axes to 0.001 mm. Nested per-layer padstack size forms are
intentionally left untouched.

The supplied expression is mutated in place, consistent with the existing
KiCad Monkey filter operations, and is also returned in the result.

parse_sexp

function
from kicad_monkey import parse_sexp
def parse_sexp(sexp: 'str', *, source_path: 'Any' = None) -> 'Any'

Parse one KiCad S-expression into the existing list-tree representation.

``source_path`` is optional; when set, any ``SexprError`` raised
out of this call carries the path so callers can surface
``file:line:col`` diagnostics without wrapping the call themselves.

parse_sexp_span

function
from kicad_monkey import parse_sexp_span
def parse_sexp_span(span: 'SexpFormSpan') -> 'Any'

Parse a selected form span into the normal nested-list representation.

parse_version

function
from kicad_monkey import parse_version
def parse_version(raw_version: 'str') -> 'Version'

Parse a supported date-based KiCad Monkey version string.

read_kicad_pro_parameters

function
from kicad_monkey import read_kicad_pro_parameters
def read_kicad_pro_parameters(filepath: 'Path') -> 'dict[str, str]'

Extract text_variables (project parameters) from a KiCad .kicad_pro file.

Args:
filepath: Path to .kicad_pro file

Returns:
Dictionary of parameter name -> value from text_variables section.
Returns empty dict if file doesn't exist or has no text_variables.

Example:
>>> params = read_kicad_pro_parameters(Path("project.kicad_pro"))
>>> log.info(params.get("CCA_CODENAME"))
"my-board"

remove_element

function
from kicad_monkey import remove_element
def remove_element(sexp: 'list', name: 'str') -> 'Optional[list]'

Remove the first child element matching ``name`` in place.

Returns the removed element or None if no match was found.

replace_element

function
from kicad_monkey import replace_element
def replace_element(sexp: 'list', name: 'str', new_elem: 'list') -> 'bool'

Replace the first child element matching ``name`` in place.

Returns True if a replacement happened, False if no match was found.

set_value

function
from kicad_monkey import set_value
def set_value(sexp: 'list', name: 'str', value: 'Any') -> 'None'

Set ``(name value)`` on ``sexp`` in place — replaces if present, appends otherwise.

Always emits the sub-list form ``[name, value]``. The bare-flag form
(``name`` as a string token) is not used by this helper; callers that
need bare flags should manipulate the list directly.

version

function
from kicad_monkey import version
def version() -> 'Version'

Return the installed distribution version, falling back to source metadata.

kicad-monkey v2026.11.30·Docs updated 2026.12.01 15:43 UTC (fd9b75b)