API Reference

This section contains the auto-generated API documentation for all modules in kicad-sch-api.

Core Package

kicad-sch-api: Professional KiCAD Schematic Manipulation Library

A modern, high-performance Python library for programmatic manipulation of KiCAD schematic files with exact format preservation, advanced component management, and AI agent integration.

Key Features: - Exact format preservation (output matches KiCAD exactly) - Enhanced object model with intuitive API - Symbol library caching and management - Multi-source component intelligence - Native MCP server for AI agent integration - Professional error handling and validation

Basic Usage:

import kicad_sch_api as ksa

# Load schematic sch = ksa.Schematic(β€˜my_circuit.kicad_sch’)

# Add components resistor = sch.components.add(β€˜Device:R’, ref=’R1’, value=’10k’, pos=(100, 100))

# Modify properties resistor.footprint = β€˜Resistor_SMD:R_0603_1608Metric’

# Save with exact format preservation sch.save()

Advanced Usage:

# Bulk operations resistors = sch.components.filter(lib_id=’Device:R’) for r in resistors:

r.properties[β€˜Tolerance’] = β€˜1%’

# Library management sch.libraries.add_path(β€˜/path/to/custom/symbols.kicad_sym’)

# Validation issues = sch.validate() if issues:

print(f”Found {len(issues)} validation issues”)

class kicad_sch_api.Component(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Bases: object

Enhanced wrapper for schematic components with modern API.

Provides intuitive access to component properties, pins, and operations while maintaining exact format preservation for professional use.

__init__(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Initialize component wrapper.

Parameters:
  • symbol_data – Underlying symbol data

  • parent_collection – Parent collection for updates

__repr__() str[source]

Detailed representation.

__str__() str[source]

String representation.

copy_properties_from(other: Component)[source]

Copy all properties from another component.

property footprint: str | None

Component footprint.

get_pin(pin_number: str) SchematicPin | None[source]

Get pin by number.

get_pin_position(pin_number: str) Point | None[source]

Get absolute position of pin.

get_property(name: str, default: str | None = None) str | None[source]

Get property value by name.

get_symbol_definition() SymbolDefinition | None[source]

Get the symbol definition from library cache.

property in_bom: bool

Whether component appears in bill of materials.

property lib_id: str

R’).

Type:

Library ID (e.g., β€˜Device

property library: str

Library name.

list_pins() List[Dict[str, Any]][source]

List all pins for this component.

Returns:

  • number: Pin number (str)

  • name: Pin name (str)

  • type: Pin electrical type (str)

  • position: Absolute pin position (Point)

Return type:

List of pin dictionaries with keys

Example

>>> comp = sch.components.get("U1")
>>> pins = comp.list_pins()
>>> for pin in pins:
...     print(f"Pin {pin['number']}: {pin['name']} ({pin['type']})")
Pin 1: GND (POWER_IN)
Pin 2: 3V3 (POWER_IN)
move(x: float, y: float)[source]

Move component to new position.

property on_board: bool

Whether component appears on PCB.

property pin_uuids: Dict[str, str]

Dictionary mapping pin numbers to their UUIDs.

property pins: List[SchematicPin]

List of component pins.

property position: Point

Component position.

property properties: Dict[str, str]

Dictionary of all component properties.

property reference: str

Component reference (e.g., β€˜R1’).

remove_property(name: str) bool[source]

Remove property by name.

rotate(angle: float)[source]

Rotate component by angle (degrees).

property rotation: float

Component rotation in degrees.

set_property(name: str, value: str)[source]

Set property value with validation.

show_pins() None[source]

Display pin information in readable table format.

Prints a formatted table showing pin numbers, names, and types for all pins on this component. Useful for interactive exploration and debugging.

Example

>>> comp = sch.components.get("U1")
>>> comp.show_pins()

Pins for U1 (RF_Module:ESP32-WROOM-32): Pin# Name Type β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”- 1 GND POWER_IN 2 3V3 POWER_IN 3 EN INPUT …

property symbol_name: str

Symbol name within library.

to_dict() Dict[str, Any][source]

Convert component to dictionary representation.

translate(dx: float, dy: float)[source]

Translate component by offset.

update_from_library() bool[source]

Update component pins and metadata from library definition.

property uuid: str

Component UUID.

validate() List[ValidationIssue][source]

Validate this component.

property value: str

Component value (e.g., β€˜10k’).

class kicad_sch_api.ComponentCollection(components: List[SchematicSymbol] = None, parent_schematic=None)[source]

Bases: BaseCollection[Component]

Collection class for efficient component management.

Inherits from BaseCollection for standard operations and adds component-specific functionality including reference, lib_id, and value-based indexing.

Provides fast lookup, filtering, and bulk operations for schematic components. Optimized for schematics with hundreds or thousands of components.

__contains__(reference: str) bool[source]

Check if reference exists.

__getitem__(key: int | str) Component[source]

Get component by index, UUID, or reference.

Parameters:

key – Integer index, UUID string, or reference string

Returns:

Component at the specified location

Raises:
__init__(components: List[SchematicSymbol] = None, parent_schematic=None)[source]

Initialize component collection.

Parameters:
  • components – Initial list of component data

  • parent_schematic – Reference to parent Schematic object (for hierarchy context)

add(lib_id: str, reference: str | None = None, value: str = '', position: Point | Tuple[float, float] | None = None, footprint: str | None = None, unit: int = 1, rotation: float = 0.0, component_uuid: str | None = None, grid_units: bool = False, grid_size: float = 1.27, **properties) Component[source]

Add a new component to the schematic.

Parameters:
  • lib_id – Library identifier (e.g., β€œDevice:R”)

  • reference – Component reference (auto-generated if None)

  • value – Component value

  • position – Component position in mm (or grid units if grid_units=True)

  • footprint – Component footprint

  • unit – Unit number for multi-unit components (1-based)

  • rotation – Component rotation in degrees (0, 90, 180, 270)

  • component_uuid – Specific UUID for component (auto-generated if None)

  • grid_units – If True, interpret position as grid units instead of mm

  • grid_size – Grid size in mm (default 1.27mm = 50 mil KiCAD standard)

  • **properties – Additional component properties

Returns:

Newly created Component

Raises:
  • ValidationError – If component data is invalid

  • LibraryError – If the KiCAD symbol library is not found

Examples

# Position in millimeters (default) sch.components.add(β€˜Device:R’, β€˜R1’, β€˜10k’, position=(25.4, 50.8))

# Position in grid units (cleaner for parametric design) sch.components.add(β€˜Device:R’, β€˜R1’, β€˜10k’, position=(20, 40), grid_units=True)

add_ic(lib_id: str, reference_prefix: str, position: Point | Tuple[float, float] | None = None, value: str = '', footprint: str | None = None, layout_style: str = 'vertical', **properties) ICManager[source]

Add a multi-unit IC with automatic unit placement.

Parameters:
  • lib_id – Library identifier for the IC (e.g., β€œ74xx:7400”)

  • reference_prefix – Base reference (e.g., β€œU1” β†’ U1A, U1B, etc.)

  • position – Base position for auto-layout (auto-placed if None)

  • value – IC value (defaults to symbol name)

  • footprint – IC footprint

  • layout_style – Layout algorithm (β€œvertical”, β€œgrid”, β€œfunctional”)

  • **properties – Common properties for all units

Returns:

ICManager object for position overrides and management

Example

ic = sch.components.add_ic(β€œ74xx:7400”, β€œU1”, position=(100, 100)) ic.place_unit(1, position=(150, 80)) # Override Gate A position

bulk_update(criteria: Dict[str, Any], updates: Dict[str, Any]) int[source]

Update multiple components matching criteria.

Parameters:
  • criteria – Filter criteria (same as filter method)

  • updates – Dictionary of property updates

Returns:

Number of components updated

filter(**criteria) List[Component][source]

Filter components by various criteria.

Parameters:
  • lib_id – Filter by library ID

  • value – Filter by value (exact match)

  • value_pattern – Filter by value pattern (contains)

  • reference_pattern – Filter by reference pattern

  • footprint – Filter by footprint

  • in_area – Filter by area (tuple of (x1, y1, x2, y2))

Returns:

List of matching components

filter_by_type(component_type: str) List[Component][source]

Filter components by type (e.g., β€˜R’ for resistors).

get(reference: str) Component | None[source]

Get component by reference.

get_statistics() Dict[str, Any][source]

Get collection statistics.

in_area(x1: float, y1: float, x2: float, y2: float) List[Component][source]

Get components within rectangular area.

near_point(point: Point | Tuple[float, float], radius: float) List[Component][source]

Get components within radius of a point.

remove(reference: str) bool[source]

Remove component by reference.

Parameters:

reference – Component reference to remove (e.g., β€œR1”)

Returns:

True if component was removed, False if not found

Raises:

TypeError – If reference is not a string

Examples

sch.components.remove(β€œR1”) sch.components.remove(β€œC2”)

Note

For removing by UUID or component object, use remove_by_uuid() or remove_component() respectively. This maintains a clear, simple API contract.

remove_by_uuid(component_uuid: str) bool[source]

Remove component by UUID.

Parameters:

component_uuid – Component UUID to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If UUID is not a string

remove_component(component: Component) bool[source]

Remove component by component object.

Parameters:

component – Component object to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If component is not a Component instance

Examples

comp = sch.components.get(β€œR1”) sch.components.remove_component(comp)

sort_by_position(by_x: bool = True)[source]

Sort components by position.

sort_by_reference()[source]

Sort components by reference designator.

validate_all() List[ValidationIssue][source]

Validate all components in collection.

exception kicad_sch_api.DuplicateElementError(message: str, element_type: str = '', identifier: str = '')[source]

Bases: CollectionError

Raised when attempting to add a duplicate element.

__init__(message: str, element_type: str = '', identifier: str = '')[source]

Initialize duplicate element error.

Parameters:
  • message – Error message

  • element_type – Type of element (e.g., β€˜component’, β€˜wire’, β€˜junction’)

  • identifier – The duplicate identifier (e.g., β€˜R1’, UUID)

exception kicad_sch_api.ElementNotFoundError(message: str, element_type: str = '', identifier: str = '')[source]

Bases: CollectionError

Raised when an element is not found in a collection.

__init__(message: str, element_type: str = '', identifier: str = '')[source]

Initialize element not found error.

Parameters:
  • message – Error message

  • element_type – Type of element (e.g., β€˜component’, β€˜wire’, β€˜junction’)

  • identifier – The identifier used to search (e.g., β€˜R1’, UUID)

class kicad_sch_api.KiCADConfig[source]

Bases: object

Central configuration class for KiCAD schematic API.

get_property_position(property_name: str, component_pos: Tuple[float, float], offset_index: int = 0, component_rotation: float = 0) Tuple[float, float, float][source]

Calculate property position relative to component, accounting for component rotation.

Parameters:
  • property_name – Name of the property (Reference, Value, etc.)

  • component_pos – (x, y) position of component

  • offset_index – Stacking offset for multiple properties

  • component_rotation – Rotation of the component in degrees (0, 90, 180, 270)

Returns:

Tuple of (x, y, rotation) for the property

should_add_title_block(name: str) bool[source]

Determine if a schematic name should generate a title block.

exception kicad_sch_api.KiCadSchError[source]

Bases: Exception

Base exception for all kicad-sch-api errors.

class kicad_sch_api.PinInfo(number: str, name: str, position: Point, electrical_type: PinType = PinType.PASSIVE, shape: PinShape = PinShape.LINE, length: float = 2.54, orientation: float = 0.0, uuid: str = '')[source]

Bases: object

Complete pin information for a component pin.

This dataclass provides comprehensive pin metadata including position, electrical properties, and graphical representation. Positions are in schematic coordinates (absolute positions accounting for component rotation and mirroring).

__post_init__() None[source]

Validate and normalize pin information.

electrical_type: PinType = 'passive'
length: float = 2.54
name: str
number: str
orientation: float = 0.0
position: Point
shape: PinShape = 'line'
to_dict() Dict[str, Any][source]

Convert pin info to dictionary representation.

uuid: str = ''
class kicad_sch_api.Schematic(schematic_data: Dict[str, Any] = None, file_path: str | None = None, name: str | None = None)[source]

Bases: object

Professional KiCAD schematic manipulation class with manager-based architecture.

Features: - Exact format preservation - Enhanced component management with fast lookup - Advanced library integration - Comprehensive validation - Performance optimization for large schematics - AI agent integration via MCP - Modular architecture with specialized managers

This class provides a modern, intuitive API while maintaining exact compatibility with KiCAD’s native file format through specialized manager classes.

__enter__()[source]

Enter atomic operation context.

__exit__(exc_type, exc_val, exc_tb)[source]

Exit atomic operation context.

__init__(schematic_data: Dict[str, Any] = None, file_path: str | None = None, name: str | None = None)[source]

Initialize schematic object with manager-based architecture.

Parameters:
  • schematic_data – Parsed schematic data

  • file_path – Original file path (for format preservation)

  • name – Project name for component instances

__repr__() str[source]

Detailed representation.

__str__() str[source]

String representation.

add_global_label(text: str, position: Point | Tuple[float, float], shape: str = 'input', effects: Dict[str, Any] | None = None) str[source]

Add a global label for project-wide connections.

Parameters:
  • text – Label text

  • position – Label position

  • shape – Shape type

  • effects – Text effects

Returns:

UUID of created global label

add_hierarchical_label(text: str, position: Point | Tuple[float, float], shape: str = 'input', rotation: float = 0.0, size: float = 1.27, effects: Dict[str, Any] | None = None) str[source]

Add a hierarchical label for sheet connections.

Parameters:
  • text – Label text

  • position – Label position

  • shape – Shape type (input, output, bidirectional, tri_state, passive)

  • rotation – Label rotation in degrees (default 0)

  • size – Label text size (default 1.27)

  • effects – Text effects

Returns:

UUID of created hierarchical label

add_image(position: Point | Tuple[float, float], scale: float = 1.0, data: str | None = None) str[source]

Add an image to the schematic.

Parameters:
  • position – Image position

  • scale – Image scale factor

  • data – Base64 encoded image data

Returns:

UUID of created image

add_label(text: str, position: Point | Tuple[float, float] | None = None, pin: Tuple[str, str] | None = None, effects: Dict[str, Any] | None = None, rotation: float | None = None, size: float | None = None, uuid: str | None = None, grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a text label to the schematic.

Parameters:
  • text – Label text content

  • position – Label position in mm (or grid units if grid_units=True, required if pin not provided)

  • pin – Pin to attach label to as (component_ref, pin_number) tuple (alternative to position)

  • effects – Text effects (size, font, etc.)

  • rotation – Label rotation in degrees (default 0, or auto-calculated if pin provided)

  • size – Text size override (default from effects)

  • uuid – Specific UUID for label (auto-generated if None)

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created label

Raises:

ValueError – If neither position nor pin is provided, or if pin is not found

add_rectangle(start: Point | Tuple[float, float], end: Point | Tuple[float, float], stroke_width: float = 0.127, stroke_type: str = 'solid', fill_type: str = 'none', stroke_color: Tuple[int, int, int, float] | None = None, fill_color: Tuple[int, int, int, float] | None = None, grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a rectangle to the schematic.

Parameters:
  • start – Top-left corner position in mm (or grid units if grid_units=True)

  • end – Bottom-right corner position in mm (or grid units if grid_units=True)

  • stroke_width – Line width

  • stroke_type – Line type (solid, dash, dash_dot, dash_dot_dot, dot, or default)

  • fill_type – Fill type (none, background, etc.)

  • stroke_color – Stroke color as (r, g, b, a)

  • fill_color – Fill color as (r, g, b, a)

  • grid_units – If True, interpret positions as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created rectangle

add_sheet(name: str, filename: str, position: Point | Tuple[float, float], size: Point | Tuple[float, float], stroke_width: float | None = None, stroke_type: str = 'solid', project_name: str | None = None, page_number: str | None = None, uuid: str | None = None) str[source]

Add a hierarchical sheet to the schematic.

Parameters:
  • name – Sheet name/title

  • filename – Referenced schematic filename

  • position – Sheet position (top-left corner)

  • size – Sheet size (width, height)

  • stroke_width – Border stroke width

  • stroke_type – Border stroke type (solid, dashed, etc.)

  • project_name – Project name for this sheet

  • page_number – Page number for this sheet

  • uuid – Optional UUID for the sheet

Returns:

UUID of created sheet

add_sheet_pin(sheet_uuid: str, name: str, pin_type: str, edge: str, position_along_edge: float, uuid: str | None = None) str[source]

Add a pin to a hierarchical sheet using edge-based positioning.

Parameters:
  • sheet_uuid – UUID of the sheet to add pin to

  • name – Pin name

  • pin_type – Pin type (input, output, bidirectional, tri_state, passive)

  • edge – Edge to place pin on (β€œright”, β€œbottom”, β€œleft”, β€œtop”)

  • position_along_edge – Distance along edge from reference corner (mm)

  • uuid – Optional UUID for the pin

Returns:

UUID of created sheet pin

Edge positioning (clockwise from right):
  • β€œright”: Pins face right (0Β°), position measured from top edge

  • β€œbottom”: Pins face down (270Β°), position measured from left edge

  • β€œleft”: Pins face left (180Β°), position measured from bottom edge

  • β€œtop”: Pins face up (90Β°), position measured from left edge

Example

>>> # Sheet at (100, 100) with size (50, 40)
>>> sch.add_sheet_pin(
...     sheet_uuid=sheet_id,
...     name="DATA_IN",
...     pin_type="input",
...     edge="left",
...     position_along_edge=20  # 20mm from top on left edge
... )
add_text(text: str, position: Point | Tuple[float, float], rotation: float = 0.0, size: float = 1.27, exclude_from_sim: bool = False, effects: Dict[str, Any] | None = None, grid_units: bool | None = None, grid_size: float | None = None, bold: bool = False, italic: bool = False, thickness: float | None = None, color: Tuple[int, int, int, float] | None = None, face: str | None = None) str[source]

Add free text annotation to the schematic.

Parameters:
  • text – Text content

  • position – Text position in mm (or grid units if grid_units=True)

  • rotation – Text rotation in degrees

  • size – Text size

  • exclude_from_sim – Whether to exclude from simulation

  • effects – (Deprecated) Text effects dictionary

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

  • bold – Bold font flag

  • italic – Italic font flag

  • thickness – Stroke width (None = use default)

  • color – RGBA color tuple (r, g, b, a) where RGB are 0-255 and A is 0-1

  • face – Font face name (None = use default)

Returns:

UUID of created text

add_text_box(text: str, position: Point | Tuple[float, float], size: Point | Tuple[float, float], rotation: float = 0.0, font_size: float = 1.27, margins: Tuple[float, float, float, float] | None = None, stroke_width: float | None = None, stroke_type: str = 'solid', fill_type: str = 'none', justify_horizontal: str = 'left', justify_vertical: str = 'top', exclude_from_sim: bool = False, effects: Dict[str, Any] | None = None, stroke: Dict[str, Any] | None = None) str[source]

Add a text box with border to the schematic.

Parameters:
  • text – Text content

  • position – Top-left position

  • size – Box size (width, height)

  • rotation – Text rotation in degrees

  • font_size – Text font size

  • margins – Box margins (top, bottom, left, right)

  • stroke_width – Border stroke width

  • stroke_type – Border stroke type (solid, dash, etc.)

  • fill_type – Fill type (none, outline, background)

  • justify_horizontal – Horizontal justification

  • justify_vertical – Vertical justification

  • exclude_from_sim – Whether to exclude from simulation

  • effects – Text effects (legacy)

  • stroke – Border stroke settings (legacy)

Returns:

UUID of created text box

add_wire(start: Point | Tuple[float, float], end: Point | Tuple[float, float], grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a wire connection between two points.

Parameters:
  • start – Start point in mm (or grid units if grid_units=True)

  • end – End point in mm (or grid units if grid_units=True)

  • grid_units – If True, interpret positions as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created wire

add_wire_between_pins(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) str | None[source]

Add wire between two component pins.

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

Returns:

Wire UUID or None if either pin not found

add_wire_to_pin(start: Point | Tuple[float, float], component_ref: str, pin_number: str) str | None[source]

Add wire from arbitrary position to component pin.

Parameters:
  • start – Start position

  • component_ref – Component reference

  • pin_number – Pin number

Returns:

Wire UUID or None if pin not found

are_pins_connected(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) bool[source]

Check if two pins are electrically connected.

Performs full connectivity analysis including connections through: - Direct wires - Junctions - Labels (local/global/hierarchical) - Power symbols - Hierarchical sheets

Parameters:
  • component1_ref – First component reference (e.g., β€œR1”)

  • pin1_number – First pin number

  • component2_ref – Second component reference (e.g., β€œR2”)

  • pin2_number – Second pin number

Returns:

True if pins are electrically connected, False otherwise

auto_route_pins(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str, routing_strategy: str = 'direct') List[str][source]

Auto-route between two component pins.

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

  • routing_strategy – Routing strategy (β€œdirect”, β€œorthogonal”, β€œmanhattan”)

Returns:

List of wire UUIDs created

backup(suffix: str = '.backup') Path[source]

Create a backup of the current schematic file.

Parameters:

suffix – Backup file suffix

Returns:

Path to backup file

property bus_entries: BusEntryCollection

Collection of all bus entry elements in the schematic.

property components: ComponentCollection

Collection of all components in the schematic.

connect_pins_with_wire(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) str | None[source]

Connect two component pins with a wire (alias for add_wire_between_pins).

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

Returns:

Wire UUID or None if either pin not found

classmethod create(name: str = 'Untitled', version: str = None, generator: str = None, generator_version: str = None, paper: str = None, uuid: str = None) Schematic[source]

Create a new empty schematic with configurable parameters.

Parameters:
  • name – Schematic name

  • version – KiCAD version (default from config)

  • generator – Generator name (default from config)

  • generator_version – Generator version (default from config)

  • paper – Paper size (default from config)

  • uuid – Specific UUID (auto-generated if None)

Returns:

New empty Schematic object

draw_bounding_box(bbox: BoundingBox, stroke_width: float = 0.127, stroke_color: str | None = None, stroke_type: str = 'solid') str[source]

Draw a single bounding box as a rectangle.

Parameters:
  • bbox – BoundingBox to draw

  • stroke_width – Line width

  • stroke_color – Line color name (red, green, blue, etc.) or None

  • stroke_type – Line type (solid, dashed, etc.)

Returns:

UUID of created rectangle

draw_component_bounding_boxes(include_properties: bool = False, stroke_width: float = 0.127, stroke_color: str = 'green', stroke_type: str = 'solid') List[str][source]

Draw bounding boxes for all components.

Parameters:
  • include_properties – Whether to include properties in bounding box

  • stroke_width – Line width

  • stroke_color – Line color

  • stroke_type – Line type

Returns:

List of rectangle UUIDs created

export_bom(**kwargs)[source]

Export Bill of Materials (BOM) from this schematic.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.bom.export_bom() - output_path: Path for BOM file - fields: List of fields to export - group_by: Fields to group by - exclude_dnp: Exclude Do-Not-Populate components - And many more options…

Returns:

Path to generated BOM file

Example

>>> bom = sch.export_bom(
...     fields=['Reference', 'Value', 'Footprint', 'MPN'],
...     group_by=['Value', 'Footprint'],
...     exclude_dnp=True,
... )
export_dxf(**kwargs)[source]

Export schematic as DXF.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_dxf()

Returns:

List of paths to generated DXF files

Example

>>> dxfs = sch.export_dxf()
export_netlist(format='kicadsexpr', **kwargs)[source]

Export netlist from this schematic.

This requires the schematic to be saved first.

Parameters:
  • format – Netlist format (default: β€˜kicadsexpr’) - kicadsexpr: KiCad S-expression (default) - kicadxml: KiCad XML - spice: SPICE netlist - spicemodel: SPICE with models - cadstar, orcadpcb2, pads, allegro

  • **kwargs – Arguments passed to cli.netlist.export_netlist()

Returns:

Path to generated netlist file

Example

>>> netlist = sch.export_netlist(format='spice')
>>> print(f"Netlist: {netlist}")
export_pdf(**kwargs)[source]

Export schematic as PDF.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_pdf() - output_path: Path for PDF file - theme: Color theme - black_and_white: B&W export - And more options…

Returns:

Path to generated PDF file

Example

>>> pdf = sch.export_pdf(theme='Kicad Classic')
export_svg(**kwargs)[source]

Export schematic as SVG.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_svg() - output_dir: Output directory - theme: Color theme - black_and_white: B&W export - And more options…

Returns:

List of paths to generated SVG files

Example

>>> svgs = sch.export_svg()
>>> for svg in svgs:
...     print(f"Generated: {svg}")
export_to_python(output_path: str | Path, template: str = 'default', include_hierarchy: bool = True, format_code: bool = True, add_comments: bool = True) Path[source]

Export schematic to executable Python code.

Generates Python code that uses kicad-sch-api to recreate this schematic programmatically.

Parameters:
  • output_path – Output .py file path

  • template – Code template style (β€˜minimal’, β€˜default’, β€˜verbose’, β€˜documented’)

  • include_hierarchy – Include hierarchical sheets

  • format_code – Format code with Black

  • add_comments – Add explanatory comments

Returns:

Path to generated Python file

Raises:

CodeGenerationError – If code generation fails

Example

>>> sch = Schematic.load('circuit.kicad_sch')
>>> sch.export_to_python('circuit.py')
PosixPath('circuit.py')
>>> sch.export_to_python('circuit.py',
...                      template='verbose',
...                      add_comments=True)
PosixPath('circuit.py')
property file_path: Path | None

Current file path.

property generator: str | None

Generator string (e.g., β€˜eeschema’).

get_component_pin_position(reference: str, pin_number: str) Point | None[source]

Get the absolute position of a component pin.

Parameters:
  • reference – Component reference (e.g., β€œR1”)

  • pin_number – Pin number to find (e.g., β€œ1”, β€œ2”)

Returns:

Absolute position of the pin, or None if not found

get_connected_pins(component_ref: str, pin_number: str) List[Tuple[str, str]][source]

Get all pins electrically connected to a specific pin.

Parameters:
  • component_ref – Component reference (e.g., β€œR1”)

  • pin_number – Pin number

Returns:

List of (reference, pin_number) tuples for all connected pins

get_net_for_pin(component_ref: str, pin_number: str)[source]

Get the electrical net connected to a specific pin.

Parameters:
  • component_ref – Component reference (e.g., β€œR1”)

  • pin_number – Pin number

Returns:

Net object if pin is connected, None otherwise

get_statistics() Dict[str, Any][source]

Get comprehensive schematic statistics.

get_validation_summary() Dict[str, Any][source]

Get validation summary statistics.

Returns:

Summary dictionary with counts and severity

property hierarchical_labels: LabelCollection

Collection of all hierarchical label elements in the schematic.

property hierarchy

Advanced hierarchy manager for complex hierarchical designs.

Provides features for: - Sheet reuse tracking (sheets used multiple times) - Cross-sheet signal tracking - Sheet pin validation - Hierarchy flattening - Signal tracing through hierarchy

property junctions: JunctionCollection

Collection of all junctions in the schematic.

property labels: LabelCollection

Collection of all label elements in the schematic.

property library

Access to symbol library cache for introspection.

Provides get_symbol_info() for querying multi-unit component metadata.

Example

info = sch.library.get_symbol_info(β€œAmplifier_Operational:TL072”) print(f”Units: {info.unit_count}”)

list_component_pins(reference: str) List[Tuple[str, Point]][source]

List all pins for a component with their absolute positions.

Parameters:

reference – Component reference (e.g., β€œR1”)

Returns:

List of (pin_number, absolute_position) tuples

classmethod load(file_path: str | Path) Schematic[source]

Load a KiCAD schematic file.

Parameters:

file_path – Path to .kicad_sch file

Returns:

Loaded Schematic object

Raises:
property modified: bool

Whether schematic has been modified since last save.

property nets: NetCollection

Collection of all electrical nets in the schematic.

property no_connects: NoConnectCollection

Collection of all no-connect elements in the schematic.

remove_hierarchical_label(label_uuid: str) bool[source]

Remove a hierarchical label by UUID.

Parameters:

label_uuid – UUID of hierarchical label to remove

Returns:

True if hierarchical label was removed, False if not found

remove_label(label_uuid: str) bool[source]

Remove a label by UUID.

Parameters:

label_uuid – UUID of label to remove

Returns:

True if label was removed, False if not found

remove_rectangle(rect_uuid: str) bool[source]

Remove a rectangle by UUID.

Parameters:

rect_uuid – UUID of rectangle to remove

Returns:

True if removed, False if not found

remove_sheet(sheet_uuid: str) bool[source]

Remove a sheet by UUID.

Parameters:

sheet_uuid – UUID of sheet to remove

Returns:

True if sheet was removed, False if not found

remove_wire(wire_uuid: str) bool[source]

Remove a wire by UUID.

Parameters:

wire_uuid – UUID of wire to remove

Returns:

True if wire was removed, False if not found

run_erc(**kwargs)[source]

Run Electrical Rule Check (ERC) on this schematic.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.erc.run_erc() - output_path: Path for ERC report - format: β€˜json’ or β€˜report’ - severity: β€˜all’, β€˜error’, β€˜warning’, β€˜exclusions’ - units: β€˜mm’, β€˜in’, β€˜mils’

Returns:

ErcReport with violations and summary

Example

>>> report = sch.run_erc()
>>> if report.has_errors():
...     print(f"Found {report.error_count} errors")
save(file_path: str | Path | None = None, preserve_format: bool = True)[source]

Save schematic to file.

Parameters:
  • file_path – Output file path (uses current path if None)

  • preserve_format – Whether to preserve exact formatting

Raises:

ValidationError – If schematic data is invalid

save_as(file_path: str | Path, preserve_format: bool = True)[source]

Save schematic to a new file path.

set_hierarchy_context(parent_uuid: str, sheet_uuid: str) None[source]

Set hierarchical context for this schematic (for child schematics in hierarchical designs).

This method configures a child schematic to be part of a hierarchical design. Components added after this call will automatically have the correct hierarchical instance path for proper annotation in KiCad.

Parameters:
  • parent_uuid – UUID of the parent schematic

  • sheet_uuid – UUID of the sheet instance in the parent schematic

Example

>>> # Create parent schematic
>>> main = ksa.create_schematic("MyProject")
>>> parent_uuid = main.uuid
>>>
>>> # Add sheet to parent and get its UUID
>>> sheet_uuid = main.sheets.add_sheet(
...     name="Power Supply",
...     filename="power.kicad_sch",
...     position=(50, 50),
...     size=(100, 100),
...     project_name="MyProject"
... )
>>>
>>> # Create child schematic with hierarchy context
>>> power = ksa.create_schematic("MyProject")
>>> power.set_hierarchy_context(parent_uuid, sheet_uuid)
>>>
>>> # Components added now will have correct hierarchical path
>>> vreg = power.components.add('Device:R', 'U1', 'AMS1117-3.3')

Note

  • This must be called BEFORE adding components to the child schematic

  • Both parent and child schematics must use the same project name

  • The hierarchical path will be: /{parent_uuid}/{sheet_uuid}

set_paper_size(paper: str) None[source]

Set paper size for the schematic.

Parameters:

paper – Paper size (A4, A3, etc.)

set_title_block(title: str = '', date: str = '', rev: str = '', company: str = '', comments: Dict[int, str] | None = None) None[source]

Set title block information.

Parameters:
  • title – Schematic title

  • date – Date

  • rev – Revision

  • company – Company name

  • comments – Comment fields (1-9)

property sheets

Sheet manager for hierarchical sheet operations.

property texts: TextCollection

Collection of all text elements in the schematic.

property title_block: Dict[str, Any]

Title block information.

property uuid: str | None

Schematic UUID.

validate() List[ValidationIssue][source]

Perform comprehensive schematic validation.

Returns:

List of validation issues found

property version: str | None

KiCAD version string.

property wires: WireCollection

Collection of all wires in the schematic.

class kicad_sch_api.SymbolLibraryCache(cache_dir: Path | None = None, enable_persistence: bool = True)[source]

Bases: object

High-performance cache for KiCAD symbol libraries.

Features: - Intelligent caching with performance metrics - Fast symbol lookup and indexing - Library discovery and management - Memory-efficient storage - Cache invalidation based on file modification time

__init__(cache_dir: Path | None = None, enable_persistence: bool = True)[source]

Initialize the symbol cache.

Parameters:
  • cache_dir – Directory to store cached symbol data

  • enable_persistence – Whether to persist cache to disk

add_library_path(library_path: str | Path) bool[source]

Add a library path to the cache.

Parameters:

library_path – Path to .kicad_sym file

Returns:

True if library was added successfully

clear_cache()[source]

Clear all cached symbol data.

discover_libraries(search_paths: List[str | Path] = None) int[source]

Automatically discover KiCAD symbol libraries.

Searches environment variables and system paths for KiCAD symbol libraries. Supports version-flexible discovery across KiCAD 7, 8, 9, and custom installations.

Environment variables checked: - KICAD_SYMBOL_DIR (generic, supports : or ; separated paths) - KICAD9_SYMBOL_DIR (KiCAD 9 specific) - KICAD8_SYMBOL_DIR (KiCAD 8 specific) - KICAD7_SYMBOL_DIR (KiCAD 7 specific)

Parameters:

search_paths – Optional custom directories to search for .kicad_sym files. If None, uses environment variables + default system paths.

Returns:

Number of libraries discovered and added

get_library_symbols(library_name: str) List[SymbolDefinition][source]

Get all symbols from a specific library.

get_performance_stats() Dict[str, Any][source]

Get cache performance statistics.

get_symbol(lib_id: str) SymbolDefinition | None[source]

Get symbol definition by lib_id.

Parameters:

lib_id – Symbol identifier (e.g., β€œDevice:R”)

Returns:

Symbol definition if found, None otherwise

get_symbol_info(lib_id: str)[source]

Get symbol metadata for library introspection.

Returns SymbolInfo with unit count, names, and other metadata. Used by LLMs to query multi-unit component information before adding.

Parameters:

lib_id – Library identifier (e.g., β€œAmplifier_Operational:TL072”)

Returns:

SymbolInfo object with symbol metadata

Raises:

LibraryError – If symbol not found

Example

info = cache.get_symbol_info(β€œAmplifier_Operational:TL072”) print(f”Units: {info.unit_count}”) # 3 print(f”Unit names: {info.unit_names}”) # {1: β€œA”, 2: β€œB”, 3: β€œC”}

search_symbols(query: str, library: str | None = None, limit: int = 50) List[SymbolDefinition][source]

Search for symbols by name, description, or keywords.

Parameters:
  • query – Search query string

  • library – Optional library name to search within

  • limit – Maximum number of results

Returns:

List of matching symbol definitions

exception kicad_sch_api.ValidationError(message: str, issues: List[ValidationIssue] | None = None, field: str = '', value: Any = None)[source]

Bases: KiCadSchError

Raised when validation fails.

Supports rich error context with field/value information and can collect multiple validation issues.

__init__(message: str, issues: List[ValidationIssue] | None = None, field: str = '', value: Any = None)[source]

Initialize validation error with context.

Parameters:
  • message – Error message describing the validation failure

  • issues – List of validation issues (for collecting multiple errors)

  • field – The field name that failed validation

  • value – The invalid value that was provided

add_issue(issue: ValidationIssue) None[source]

Add a validation issue to this error.

get_errors() List[ValidationIssue][source]

Get only error-level issues.

get_warnings() List[ValidationIssue][source]

Get only warning-level issues.

class kicad_sch_api.ValidationIssue(category: str, message: str, level: ValidationLevel, context: Dict[str, Any] | None = None, suggestion: str | None = None)[source]

Bases: object

Single validation issue with context.

category: str
context: Dict[str, Any] | None = None
level: ValidationLevel
message: str
suggestion: str | None = None
kicad_sch_api.create_schematic(name: str = 'Untitled') Schematic[source]

Create a new empty schematic.

Parameters:

name – Optional schematic name

Returns:

New empty Schematic object

Example

>>> sch = ksa.create_schematic("My New Circuit")
>>> sch.components.add('Device:R', 'R1', '10k')
kicad_sch_api.get_symbol_cache() SymbolLibraryCache[source]

Get the global symbol cache instance.

kicad_sch_api.get_symbol_info(lib_id: str) SymbolDefinition | None[source]

Get symbol information from the library.

Convenience function that uses the global symbol cache to retrieve complete symbol information including pins, description, and metadata.

Parameters:

lib_id – Library identifier (e.g., β€œDevice:R”, β€œRF_Module:ESP32-WROOM-32”)

Returns:

SymbolDefinition with complete symbol information, or None if not found

Example

>>> import kicad_sch_api as ksa
>>> symbol = ksa.get_symbol_info('RF_Module:ESP32-WROOM-32')
>>> if symbol:
...     symbol.show_pins()  # Display pin table
Pins for RF_Module:ESP32-WROOM-32:
Description: WiFi/Bluetooth module
Pin#   Name                 Type
----------------------------------------
1      GND                  POWER_IN
2      3V3                  POWER_IN
...
>>> pins = symbol.list_pins()  # Get pin data
>>> print(f"Symbol has {len(pins)} pins")
kicad_sch_api.load_schematic(file_path: str) Schematic[source]

Load a KiCAD schematic file.

Parameters:

file_path – Path to .kicad_sch file

Returns:

Schematic object for manipulation

Example

>>> sch = ksa.load_schematic('my_circuit.kicad_sch')
>>> print(f"Loaded {len(sch.components)} components")
kicad_sch_api.schematic_to_python(input_path: str, output_path: str, template: str = 'default', include_hierarchy: bool = True, format_code: bool = True, add_comments: bool = True)[source]

Convert KiCad schematic to Python code (one-line convenience function).

Loads a KiCad schematic and generates executable Python code that recreates it using the kicad-sch-api library.

Parameters:
  • input_path – Input .kicad_sch file

  • output_path – Output .py file

  • template – Code template style (β€˜minimal’, β€˜default’, β€˜verbose’, β€˜documented’)

  • include_hierarchy – Include hierarchical sheets

  • format_code – Format code with Black

  • add_comments – Add explanatory comments

Returns:

Path to generated Python file

Raises:
  • FileNotFoundError – If input file doesn’t exist

  • CodeGenerationError – If code generation fails

Example

>>> import kicad_sch_api as ksa
>>> ksa.schematic_to_python('input.kicad_sch', 'output.py')
PosixPath('output.py')
>>> ksa.schematic_to_python('input.kicad_sch', 'output.py',
...                         template='minimal',
...                         add_comments=False)
PosixPath('output.py')
kicad_sch_api.search_symbols(query: str, library: str | None = None, limit: int = 50) List[SymbolDefinition][source]

Search for symbols by name, description, or keywords.

Convenience function that uses the global symbol cache to search for symbols matching the query string.

Parameters:
  • query – Search query string (searches in name, description, keywords)

  • library – Optional library name to search within (e.g., β€œDevice”, β€œRF_Module”)

  • limit – Maximum number of results to return (default: 50)

Returns:

List of SymbolDefinition objects matching the query

Example

>>> import kicad_sch_api as ksa
>>> # Search for all resistors
>>> resistors = ksa.search_symbols('resistor')
>>> for symbol in resistors:
...     print(f"{symbol.lib_id}: {symbol.description}")
>>> # Search only in Device library
>>> devices = ksa.search_symbols('capacitor', library='Device')
>>> # Search for ESP32 modules
>>> esp_modules = ksa.search_symbols('ESP32', library='RF_Module')
>>> for module in esp_modules:
...     module.show_pins()
kicad_sch_api.use_grid_units(enabled: bool = True) None[source]

Enable or disable grid units for positioning.

When enabled, all position values are interpreted as grid units (1 unit = 1.27mm, the standard KiCAD 50 mil grid).

Parameters:

enabled – If True, use grid units; if False, use millimeters

Example

>>> import kicad_sch_api as ksa
>>> ksa.use_grid_units(True)
>>> sch = ksa.create_schematic("MyCircuit")
>>> # Now positions are in grid units
>>> sch.components.add('Device:R', 'R1', '10k', position=(20, 20))  # 25.4mm, 25.4mm

Schematic

Refactored Schematic class using composition with specialized managers.

This module provides the same interface as the original Schematic class but uses composition with specialized manager classes for better separation of concerns and maintainability.

class kicad_sch_api.core.schematic.Schematic(schematic_data: Dict[str, Any] = None, file_path: str | None = None, name: str | None = None)[source]

Bases: object

Professional KiCAD schematic manipulation class with manager-based architecture.

Features: - Exact format preservation - Enhanced component management with fast lookup - Advanced library integration - Comprehensive validation - Performance optimization for large schematics - AI agent integration via MCP - Modular architecture with specialized managers

This class provides a modern, intuitive API while maintaining exact compatibility with KiCAD’s native file format through specialized manager classes.

__enter__()[source]

Enter atomic operation context.

__exit__(exc_type, exc_val, exc_tb)[source]

Exit atomic operation context.

__init__(schematic_data: Dict[str, Any] = None, file_path: str | None = None, name: str | None = None)[source]

Initialize schematic object with manager-based architecture.

Parameters:
  • schematic_data – Parsed schematic data

  • file_path – Original file path (for format preservation)

  • name – Project name for component instances

__repr__() str[source]

Detailed representation.

__str__() str[source]

String representation.

add_global_label(text: str, position: Point | Tuple[float, float], shape: str = 'input', effects: Dict[str, Any] | None = None) str[source]

Add a global label for project-wide connections.

Parameters:
  • text – Label text

  • position – Label position

  • shape – Shape type

  • effects – Text effects

Returns:

UUID of created global label

add_hierarchical_label(text: str, position: Point | Tuple[float, float], shape: str = 'input', rotation: float = 0.0, size: float = 1.27, effects: Dict[str, Any] | None = None) str[source]

Add a hierarchical label for sheet connections.

Parameters:
  • text – Label text

  • position – Label position

  • shape – Shape type (input, output, bidirectional, tri_state, passive)

  • rotation – Label rotation in degrees (default 0)

  • size – Label text size (default 1.27)

  • effects – Text effects

Returns:

UUID of created hierarchical label

add_image(position: Point | Tuple[float, float], scale: float = 1.0, data: str | None = None) str[source]

Add an image to the schematic.

Parameters:
  • position – Image position

  • scale – Image scale factor

  • data – Base64 encoded image data

Returns:

UUID of created image

add_label(text: str, position: Point | Tuple[float, float] | None = None, pin: Tuple[str, str] | None = None, effects: Dict[str, Any] | None = None, rotation: float | None = None, size: float | None = None, uuid: str | None = None, grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a text label to the schematic.

Parameters:
  • text – Label text content

  • position – Label position in mm (or grid units if grid_units=True, required if pin not provided)

  • pin – Pin to attach label to as (component_ref, pin_number) tuple (alternative to position)

  • effects – Text effects (size, font, etc.)

  • rotation – Label rotation in degrees (default 0, or auto-calculated if pin provided)

  • size – Text size override (default from effects)

  • uuid – Specific UUID for label (auto-generated if None)

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created label

Raises:

ValueError – If neither position nor pin is provided, or if pin is not found

add_rectangle(start: Point | Tuple[float, float], end: Point | Tuple[float, float], stroke_width: float = 0.127, stroke_type: str = 'solid', fill_type: str = 'none', stroke_color: Tuple[int, int, int, float] | None = None, fill_color: Tuple[int, int, int, float] | None = None, grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a rectangle to the schematic.

Parameters:
  • start – Top-left corner position in mm (or grid units if grid_units=True)

  • end – Bottom-right corner position in mm (or grid units if grid_units=True)

  • stroke_width – Line width

  • stroke_type – Line type (solid, dash, dash_dot, dash_dot_dot, dot, or default)

  • fill_type – Fill type (none, background, etc.)

  • stroke_color – Stroke color as (r, g, b, a)

  • fill_color – Fill color as (r, g, b, a)

  • grid_units – If True, interpret positions as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created rectangle

add_sheet(name: str, filename: str, position: Point | Tuple[float, float], size: Point | Tuple[float, float], stroke_width: float | None = None, stroke_type: str = 'solid', project_name: str | None = None, page_number: str | None = None, uuid: str | None = None) str[source]

Add a hierarchical sheet to the schematic.

Parameters:
  • name – Sheet name/title

  • filename – Referenced schematic filename

  • position – Sheet position (top-left corner)

  • size – Sheet size (width, height)

  • stroke_width – Border stroke width

  • stroke_type – Border stroke type (solid, dashed, etc.)

  • project_name – Project name for this sheet

  • page_number – Page number for this sheet

  • uuid – Optional UUID for the sheet

Returns:

UUID of created sheet

add_sheet_pin(sheet_uuid: str, name: str, pin_type: str, edge: str, position_along_edge: float, uuid: str | None = None) str[source]

Add a pin to a hierarchical sheet using edge-based positioning.

Parameters:
  • sheet_uuid – UUID of the sheet to add pin to

  • name – Pin name

  • pin_type – Pin type (input, output, bidirectional, tri_state, passive)

  • edge – Edge to place pin on (β€œright”, β€œbottom”, β€œleft”, β€œtop”)

  • position_along_edge – Distance along edge from reference corner (mm)

  • uuid – Optional UUID for the pin

Returns:

UUID of created sheet pin

Edge positioning (clockwise from right):
  • β€œright”: Pins face right (0Β°), position measured from top edge

  • β€œbottom”: Pins face down (270Β°), position measured from left edge

  • β€œleft”: Pins face left (180Β°), position measured from bottom edge

  • β€œtop”: Pins face up (90Β°), position measured from left edge

Example

>>> # Sheet at (100, 100) with size (50, 40)
>>> sch.add_sheet_pin(
...     sheet_uuid=sheet_id,
...     name="DATA_IN",
...     pin_type="input",
...     edge="left",
...     position_along_edge=20  # 20mm from top on left edge
... )
add_text(text: str, position: Point | Tuple[float, float], rotation: float = 0.0, size: float = 1.27, exclude_from_sim: bool = False, effects: Dict[str, Any] | None = None, grid_units: bool | None = None, grid_size: float | None = None, bold: bool = False, italic: bool = False, thickness: float | None = None, color: Tuple[int, int, int, float] | None = None, face: str | None = None) str[source]

Add free text annotation to the schematic.

Parameters:
  • text – Text content

  • position – Text position in mm (or grid units if grid_units=True)

  • rotation – Text rotation in degrees

  • size – Text size

  • exclude_from_sim – Whether to exclude from simulation

  • effects – (Deprecated) Text effects dictionary

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

  • bold – Bold font flag

  • italic – Italic font flag

  • thickness – Stroke width (None = use default)

  • color – RGBA color tuple (r, g, b, a) where RGB are 0-255 and A is 0-1

  • face – Font face name (None = use default)

Returns:

UUID of created text

add_text_box(text: str, position: Point | Tuple[float, float], size: Point | Tuple[float, float], rotation: float = 0.0, font_size: float = 1.27, margins: Tuple[float, float, float, float] | None = None, stroke_width: float | None = None, stroke_type: str = 'solid', fill_type: str = 'none', justify_horizontal: str = 'left', justify_vertical: str = 'top', exclude_from_sim: bool = False, effects: Dict[str, Any] | None = None, stroke: Dict[str, Any] | None = None) str[source]

Add a text box with border to the schematic.

Parameters:
  • text – Text content

  • position – Top-left position

  • size – Box size (width, height)

  • rotation – Text rotation in degrees

  • font_size – Text font size

  • margins – Box margins (top, bottom, left, right)

  • stroke_width – Border stroke width

  • stroke_type – Border stroke type (solid, dash, etc.)

  • fill_type – Fill type (none, outline, background)

  • justify_horizontal – Horizontal justification

  • justify_vertical – Vertical justification

  • exclude_from_sim – Whether to exclude from simulation

  • effects – Text effects (legacy)

  • stroke – Border stroke settings (legacy)

Returns:

UUID of created text box

add_wire(start: Point | Tuple[float, float], end: Point | Tuple[float, float], grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a wire connection between two points.

Parameters:
  • start – Start point in mm (or grid units if grid_units=True)

  • end – End point in mm (or grid units if grid_units=True)

  • grid_units – If True, interpret positions as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of created wire

add_wire_between_pins(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) str | None[source]

Add wire between two component pins.

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

Returns:

Wire UUID or None if either pin not found

add_wire_to_pin(start: Point | Tuple[float, float], component_ref: str, pin_number: str) str | None[source]

Add wire from arbitrary position to component pin.

Parameters:
  • start – Start position

  • component_ref – Component reference

  • pin_number – Pin number

Returns:

Wire UUID or None if pin not found

are_pins_connected(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) bool[source]

Check if two pins are electrically connected.

Performs full connectivity analysis including connections through: - Direct wires - Junctions - Labels (local/global/hierarchical) - Power symbols - Hierarchical sheets

Parameters:
  • component1_ref – First component reference (e.g., β€œR1”)

  • pin1_number – First pin number

  • component2_ref – Second component reference (e.g., β€œR2”)

  • pin2_number – Second pin number

Returns:

True if pins are electrically connected, False otherwise

auto_route_pins(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str, routing_strategy: str = 'direct') List[str][source]

Auto-route between two component pins.

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

  • routing_strategy – Routing strategy (β€œdirect”, β€œorthogonal”, β€œmanhattan”)

Returns:

List of wire UUIDs created

backup(suffix: str = '.backup') Path[source]

Create a backup of the current schematic file.

Parameters:

suffix – Backup file suffix

Returns:

Path to backup file

property bus_entries: BusEntryCollection

Collection of all bus entry elements in the schematic.

property components: ComponentCollection

Collection of all components in the schematic.

connect_pins_with_wire(component1_ref: str, pin1_number: str, component2_ref: str, pin2_number: str) str | None[source]

Connect two component pins with a wire (alias for add_wire_between_pins).

Parameters:
  • component1_ref – First component reference

  • pin1_number – First component pin number

  • component2_ref – Second component reference

  • pin2_number – Second component pin number

Returns:

Wire UUID or None if either pin not found

classmethod create(name: str = 'Untitled', version: str = None, generator: str = None, generator_version: str = None, paper: str = None, uuid: str = None) Schematic[source]

Create a new empty schematic with configurable parameters.

Parameters:
  • name – Schematic name

  • version – KiCAD version (default from config)

  • generator – Generator name (default from config)

  • generator_version – Generator version (default from config)

  • paper – Paper size (default from config)

  • uuid – Specific UUID (auto-generated if None)

Returns:

New empty Schematic object

draw_bounding_box(bbox: BoundingBox, stroke_width: float = 0.127, stroke_color: str | None = None, stroke_type: str = 'solid') str[source]

Draw a single bounding box as a rectangle.

Parameters:
  • bbox – BoundingBox to draw

  • stroke_width – Line width

  • stroke_color – Line color name (red, green, blue, etc.) or None

  • stroke_type – Line type (solid, dashed, etc.)

Returns:

UUID of created rectangle

draw_component_bounding_boxes(include_properties: bool = False, stroke_width: float = 0.127, stroke_color: str = 'green', stroke_type: str = 'solid') List[str][source]

Draw bounding boxes for all components.

Parameters:
  • include_properties – Whether to include properties in bounding box

  • stroke_width – Line width

  • stroke_color – Line color

  • stroke_type – Line type

Returns:

List of rectangle UUIDs created

export_bom(**kwargs)[source]

Export Bill of Materials (BOM) from this schematic.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.bom.export_bom() - output_path: Path for BOM file - fields: List of fields to export - group_by: Fields to group by - exclude_dnp: Exclude Do-Not-Populate components - And many more options…

Returns:

Path to generated BOM file

Example

>>> bom = sch.export_bom(
...     fields=['Reference', 'Value', 'Footprint', 'MPN'],
...     group_by=['Value', 'Footprint'],
...     exclude_dnp=True,
... )
export_dxf(**kwargs)[source]

Export schematic as DXF.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_dxf()

Returns:

List of paths to generated DXF files

Example

>>> dxfs = sch.export_dxf()
export_netlist(format='kicadsexpr', **kwargs)[source]

Export netlist from this schematic.

This requires the schematic to be saved first.

Parameters:
  • format – Netlist format (default: β€˜kicadsexpr’) - kicadsexpr: KiCad S-expression (default) - kicadxml: KiCad XML - spice: SPICE netlist - spicemodel: SPICE with models - cadstar, orcadpcb2, pads, allegro

  • **kwargs – Arguments passed to cli.netlist.export_netlist()

Returns:

Path to generated netlist file

Example

>>> netlist = sch.export_netlist(format='spice')
>>> print(f"Netlist: {netlist}")
export_pdf(**kwargs)[source]

Export schematic as PDF.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_pdf() - output_path: Path for PDF file - theme: Color theme - black_and_white: B&W export - And more options…

Returns:

Path to generated PDF file

Example

>>> pdf = sch.export_pdf(theme='Kicad Classic')
export_svg(**kwargs)[source]

Export schematic as SVG.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.export_docs.export_svg() - output_dir: Output directory - theme: Color theme - black_and_white: B&W export - And more options…

Returns:

List of paths to generated SVG files

Example

>>> svgs = sch.export_svg()
>>> for svg in svgs:
...     print(f"Generated: {svg}")
export_to_python(output_path: str | Path, template: str = 'default', include_hierarchy: bool = True, format_code: bool = True, add_comments: bool = True) Path[source]

Export schematic to executable Python code.

Generates Python code that uses kicad-sch-api to recreate this schematic programmatically.

Parameters:
  • output_path – Output .py file path

  • template – Code template style (β€˜minimal’, β€˜default’, β€˜verbose’, β€˜documented’)

  • include_hierarchy – Include hierarchical sheets

  • format_code – Format code with Black

  • add_comments – Add explanatory comments

Returns:

Path to generated Python file

Raises:

CodeGenerationError – If code generation fails

Example

>>> sch = Schematic.load('circuit.kicad_sch')
>>> sch.export_to_python('circuit.py')
PosixPath('circuit.py')
>>> sch.export_to_python('circuit.py',
...                      template='verbose',
...                      add_comments=True)
PosixPath('circuit.py')
property file_path: Path | None

Current file path.

property generator: str | None

Generator string (e.g., β€˜eeschema’).

get_component_pin_position(reference: str, pin_number: str) Point | None[source]

Get the absolute position of a component pin.

Parameters:
  • reference – Component reference (e.g., β€œR1”)

  • pin_number – Pin number to find (e.g., β€œ1”, β€œ2”)

Returns:

Absolute position of the pin, or None if not found

get_connected_pins(component_ref: str, pin_number: str) List[Tuple[str, str]][source]

Get all pins electrically connected to a specific pin.

Parameters:
  • component_ref – Component reference (e.g., β€œR1”)

  • pin_number – Pin number

Returns:

List of (reference, pin_number) tuples for all connected pins

get_net_for_pin(component_ref: str, pin_number: str)[source]

Get the electrical net connected to a specific pin.

Parameters:
  • component_ref – Component reference (e.g., β€œR1”)

  • pin_number – Pin number

Returns:

Net object if pin is connected, None otherwise

get_statistics() Dict[str, Any][source]

Get comprehensive schematic statistics.

get_validation_summary() Dict[str, Any][source]

Get validation summary statistics.

Returns:

Summary dictionary with counts and severity

property hierarchical_labels: LabelCollection

Collection of all hierarchical label elements in the schematic.

property hierarchy

Advanced hierarchy manager for complex hierarchical designs.

Provides features for: - Sheet reuse tracking (sheets used multiple times) - Cross-sheet signal tracking - Sheet pin validation - Hierarchy flattening - Signal tracing through hierarchy

property junctions: JunctionCollection

Collection of all junctions in the schematic.

property labels: LabelCollection

Collection of all label elements in the schematic.

property library

Access to symbol library cache for introspection.

Provides get_symbol_info() for querying multi-unit component metadata.

Example

info = sch.library.get_symbol_info(β€œAmplifier_Operational:TL072”) print(f”Units: {info.unit_count}”)

list_component_pins(reference: str) List[Tuple[str, Point]][source]

List all pins for a component with their absolute positions.

Parameters:

reference – Component reference (e.g., β€œR1”)

Returns:

List of (pin_number, absolute_position) tuples

classmethod load(file_path: str | Path) Schematic[source]

Load a KiCAD schematic file.

Parameters:

file_path – Path to .kicad_sch file

Returns:

Loaded Schematic object

Raises:
property modified: bool

Whether schematic has been modified since last save.

property nets: NetCollection

Collection of all electrical nets in the schematic.

property no_connects: NoConnectCollection

Collection of all no-connect elements in the schematic.

remove_hierarchical_label(label_uuid: str) bool[source]

Remove a hierarchical label by UUID.

Parameters:

label_uuid – UUID of hierarchical label to remove

Returns:

True if hierarchical label was removed, False if not found

remove_label(label_uuid: str) bool[source]

Remove a label by UUID.

Parameters:

label_uuid – UUID of label to remove

Returns:

True if label was removed, False if not found

remove_rectangle(rect_uuid: str) bool[source]

Remove a rectangle by UUID.

Parameters:

rect_uuid – UUID of rectangle to remove

Returns:

True if removed, False if not found

remove_sheet(sheet_uuid: str) bool[source]

Remove a sheet by UUID.

Parameters:

sheet_uuid – UUID of sheet to remove

Returns:

True if sheet was removed, False if not found

remove_wire(wire_uuid: str) bool[source]

Remove a wire by UUID.

Parameters:

wire_uuid – UUID of wire to remove

Returns:

True if wire was removed, False if not found

run_erc(**kwargs)[source]

Run Electrical Rule Check (ERC) on this schematic.

This requires the schematic to be saved first.

Parameters:

**kwargs – Arguments passed to cli.erc.run_erc() - output_path: Path for ERC report - format: β€˜json’ or β€˜report’ - severity: β€˜all’, β€˜error’, β€˜warning’, β€˜exclusions’ - units: β€˜mm’, β€˜in’, β€˜mils’

Returns:

ErcReport with violations and summary

Example

>>> report = sch.run_erc()
>>> if report.has_errors():
...     print(f"Found {report.error_count} errors")
save(file_path: str | Path | None = None, preserve_format: bool = True)[source]

Save schematic to file.

Parameters:
  • file_path – Output file path (uses current path if None)

  • preserve_format – Whether to preserve exact formatting

Raises:

ValidationError – If schematic data is invalid

save_as(file_path: str | Path, preserve_format: bool = True)[source]

Save schematic to a new file path.

set_hierarchy_context(parent_uuid: str, sheet_uuid: str) None[source]

Set hierarchical context for this schematic (for child schematics in hierarchical designs).

This method configures a child schematic to be part of a hierarchical design. Components added after this call will automatically have the correct hierarchical instance path for proper annotation in KiCad.

Parameters:
  • parent_uuid – UUID of the parent schematic

  • sheet_uuid – UUID of the sheet instance in the parent schematic

Example

>>> # Create parent schematic
>>> main = ksa.create_schematic("MyProject")
>>> parent_uuid = main.uuid
>>>
>>> # Add sheet to parent and get its UUID
>>> sheet_uuid = main.sheets.add_sheet(
...     name="Power Supply",
...     filename="power.kicad_sch",
...     position=(50, 50),
...     size=(100, 100),
...     project_name="MyProject"
... )
>>>
>>> # Create child schematic with hierarchy context
>>> power = ksa.create_schematic("MyProject")
>>> power.set_hierarchy_context(parent_uuid, sheet_uuid)
>>>
>>> # Components added now will have correct hierarchical path
>>> vreg = power.components.add('Device:R', 'U1', 'AMS1117-3.3')

Note

  • This must be called BEFORE adding components to the child schematic

  • Both parent and child schematics must use the same project name

  • The hierarchical path will be: /{parent_uuid}/{sheet_uuid}

set_paper_size(paper: str) None[source]

Set paper size for the schematic.

Parameters:

paper – Paper size (A4, A3, etc.)

set_title_block(title: str = '', date: str = '', rev: str = '', company: str = '', comments: Dict[int, str] | None = None) None[source]

Set title block information.

Parameters:
  • title – Schematic title

  • date – Date

  • rev – Revision

  • company – Company name

  • comments – Comment fields (1-9)

property sheets

Sheet manager for hierarchical sheet operations.

property texts: TextCollection

Collection of all text elements in the schematic.

property title_block: Dict[str, Any]

Title block information.

property uuid: str | None

Schematic UUID.

validate() List[ValidationIssue][source]

Perform comprehensive schematic validation.

Returns:

List of validation issues found

property version: str | None

KiCAD version string.

property wires: WireCollection

Collection of all wires in the schematic.

kicad_sch_api.core.schematic.create_schematic(name: str = 'New Circuit') Schematic[source]

Create a new empty schematic.

Parameters:

name – Schematic name for title block

Returns:

New Schematic object

kicad_sch_api.core.schematic.load_schematic(file_path: str | Path) Schematic[source]

Load a KiCAD schematic file.

Parameters:

file_path – Path to .kicad_sch file

Returns:

Loaded Schematic object

Collections

Base Collection

Base collection infrastructure with centralized index management.

Provides: - IndexSpec: Index specification and declaration - IndexRegistry: Centralized index management with lazy rebuilding - PropertyDict: Auto-tracking dictionary for modification detection - ValidationLevel: Configurable validation levels - BaseCollection: Abstract base class for all collections

class kicad_sch_api.collections.base.BaseCollection(items: List[T] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Bases: Generic[T], ABC

Abstract base class for all schematic element collections.

Provides unified functionality for: - Lazy index rebuilding via IndexRegistry - Automatic modification tracking - Configurable validation levels - Batch mode for performance - Consistent collection operations (add, remove, get, filter)

Subclasses must implement: - _get_item_uuid(item): Extract UUID from item - _create_item(**kwargs): Create new item instance - _get_index_specs(): Return list of IndexSpec for this collection

__contains__(item: str | T) bool[source]

Check if item or UUID is in collection.

__getitem__(index: int) T[source]

Get item by index.

__init__(items: List[T] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Initialize base collection.

Parameters:
  • items – Initial list of items

  • validation_level – Validation level for operations

__iter__() Iterator[T][source]

Iterate over items in collection.

__len__() int[source]

Number of items in collection.

add(item: T) T[source]

Add an item to the collection.

Parameters:

item – Item to add

Returns:

The added item

Raises:

ValueError – If item with same UUID already exists

all() Iterator[T][source]

Get iterator over all items in the collection.

Returns:

Iterator over all items

Example

# Iterate over all components for component in sch.components.all():

print(component.reference)

# Convert to list all_components = list(sch.components.all())

batch_mode()[source]

Context manager for batch operations.

Defers index rebuilding until the batch is complete.

Example

with collection.batch_mode():
for i in range(1000):

collection.add(create_item(i))

# Indexes rebuilt only once here

clear() None[source]

Clear all items from the collection.

filter(**criteria) List[T][source]

Filter items by attribute criteria.

Parameters:

**criteria – Attribute name/value pairs to match

Returns:

List of matching items

find(predicate: Callable[[T], bool]) List[T][source]

Find all items matching a predicate.

Parameters:

predicate – Function that returns True for matching items

Returns:

List of matching items

get(uuid: str) T | None[source]

Get an item by UUID.

Parameters:

uuid – UUID to search for

Returns:

Item if found, None otherwise

get_statistics() Dict[str, Any][source]

Get collection statistics for debugging and monitoring.

Returns:

Dictionary with collection statistics

property is_modified: bool

Whether collection has been modified.

mark_clean() None[source]

Mark collection as clean (not modified).

remove(identifier: str | T) bool[source]

Remove an item from the collection.

Parameters:

identifier – UUID string or item instance to remove

Returns:

True if item was removed, False if not found

set_validation_level(level: ValidationLevel) None[source]

Set validation level.

Parameters:

level – New validation level

property validation_level: ValidationLevel

Current validation level.

class kicad_sch_api.collections.base.BatchContext(collection: BaseCollection)[source]

Bases: object

Context manager for batch operations.

__enter__()[source]

Enter batch mode - defers index rebuilds.

__exit__(exc_type, exc_val, exc_tb)[source]

Exit batch mode and rebuild indexes if needed.

__init__(collection: BaseCollection)[source]

Initialize batch context.

Parameters:

collection – Collection to batch operations on

class kicad_sch_api.collections.base.IndexRegistry(specs: List[IndexSpec])[source]

Bases: object

Centralized registry for managing collection indexes.

Provides: - Lazy index rebuilding (only when needed) - Multiple index support (uuid, reference, lib_id, etc.) - Duplicate detection for unique indexes - Unified index management API

__init__(specs: List[IndexSpec])[source]

Initialize index registry.

Parameters:

specs – List of index specifications to manage

add_spec(spec: IndexSpec) None[source]

Add a new index specification.

Parameters:

spec – Index specification to add

get(index_name: str, key: Any) Any | None[source]

Get value from an index.

Parameters:
  • index_name – Name of the index

  • key – Key to look up

Returns:

Index value if found, None otherwise

has_key(index_name: str, key: Any) bool[source]

Check if key exists in index.

Parameters:
  • index_name – Name of the index

  • key – Key to check

Returns:

True if key exists, False otherwise

is_dirty() bool[source]

Check if indexes need rebuilding.

mark_dirty() None[source]

Mark all indexes as needing rebuild.

rebuild(items: List[Any]) None[source]

Rebuild all indexes from items.

Parameters:

items – List of items to index

Raises:

ValueError – If unique index has duplicates

class kicad_sch_api.collections.base.IndexSpec(name: str, key_func: Callable[[Any], Any], unique: bool = True, description: str = '')[source]

Bases: object

Specification for a collection index.

Defines how to build and maintain an index for fast lookups.

__post_init__()[source]

Validate index specification.

description: str = ''
key_func: Callable[[Any], Any]
name: str
unique: bool = True
class kicad_sch_api.collections.base.PropertyDict(data: Dict[str, Any] | None = None, on_modify: Callable[[], None] | None = None)[source]

Bases: MutableMapping

Dictionary that automatically tracks modifications.

Wraps a dictionary and notifies a callback when any changes occur. Implements the full MutableMapping interface.

__delitem__(key: str) None[source]

Delete item and trigger modification callback.

__getitem__(key: str) Any[source]

Get item by key.

__init__(data: Dict[str, Any] | None = None, on_modify: Callable[[], None] | None = None)[source]

Initialize property dictionary.

Parameters:
  • data – Initial dictionary data

  • on_modify – Callback to invoke when dict is modified

__iter__() Iterator[str][source]

Iterate over keys.

__len__() int[source]

Number of items.

__repr__() str[source]

String representation.

__setitem__(key: str, value: Any) None[source]

Set item and trigger modification callback.

set_callback(on_modify: Callable[[], None]) None[source]

Set or update the modification callback.

class kicad_sch_api.collections.base.ValidationLevel(*values)[source]

Bases: Enum

Validation level for collection operations.

Controls the amount of validation performed during collection operations. Higher levels provide more safety but lower performance.

BASIC = 1
NONE = 0
NORMAL = 2
PARANOID = 4
STRICT = 3
__lt__(other)[source]

Compare validation levels by value.

Component Collection

Enhanced component management with IndexRegistry integration.

This module provides the Component wrapper and ComponentCollection using the new BaseCollection infrastructure with centralized index management, lazy rebuilding, and batch mode support.

class kicad_sch_api.collections.components.Component(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Bases: object

Enhanced wrapper for schematic components.

Provides intuitive access to component properties, pins, and operations while maintaining exact format preservation. All property modifications automatically notify the parent collection for tracking.

__init__(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Initialize component wrapper.

Parameters:
  • symbol_data – Underlying symbol data

  • parent_collection – Parent collection for modification tracking

__repr__() str[source]

Detailed representation for debugging.

__str__() str[source]

String representation for display.

add_properties(props: Dict[str, str], hidden: bool = False) None[source]

Add or update multiple properties with same visibility setting.

Convenience method for bulk property operations. All properties will have the same visibility state.

Parameters:
  • props – Dictionary of property name/value pairs

  • hidden – If True, all properties will be hidden. If False, all will be visible. Default: False

Example

>>> component.add_properties({
...     "MPN": "RC0603FR-0710KL",
...     "Manufacturer": "Yageo",
...     "Supplier": "Digikey"
... }, hidden=True)
add_property(name: str, value: str, hidden: bool = False) None[source]

Add or update a component property with visibility control.

Sets the property value and manages its visibility state. If the property already exists, both value and visibility are updated.

Parameters:
  • name – Property name (e.g., β€œMPN”, β€œManufacturer”, β€œTolerance”)

  • value – Property value

  • hidden – If True, property will have (hide yes) flag in S-expression. If False, property will be visible on schematic. Default: False

Example

>>> component.add_property("MPN", "RC0603FR-0710KL", hidden=True)
>>> component.add_property("Tolerance", "1%", hidden=False)
align_pin(pin_number: str, target_position: Point | Tuple[float, float]) None[source]

Move component so that the specified pin is at the target position.

This adjusts the component’s position to align a specific pin with the target coordinates while maintaining the component’s current rotation. Useful for aligning existing components in horizontal signal flows.

Parameters:
  • pin_number – Pin number to align (e.g., β€œ1”, β€œ2”)

  • target_position – Desired position for the pin (Point or (x, y) tuple)

Raises:

ValueError – If pin_number doesn’t exist in the component

Example

# Move resistor so pin 2 is at (150, 100) r1 = sch.components.get(β€œR1”) r1.align_pin(β€œ2”, (150, 100))

# Align capacitor pin 1 on same horizontal line c1 = sch.components.get(β€œC1”) c1.align_pin(β€œ1”, (200, 100)) # Same Y as resistor pin 2

copy_properties_from(other: Component)[source]

Copy all properties from another component.

Parameters:

other – Component to copy properties from

property fields_autoplaced: bool

Whether component properties are auto-placed by KiCAD.

property footprint: str | None

R_0603_1608Metric’).

Type:

Component footprint (e.g., β€˜Resistor_SMD

get_pin(pin_number: str) SchematicPin | None[source]

Get pin by number.

Parameters:

pin_number – Pin number to find

Returns:

SchematicPin if found, None otherwise

get_pin_position(pin_number: str) Point | None[source]

Get absolute position of a pin.

Calculates the pin position accounting for component position, rotation, and mirroring.

Parameters:

pin_number – Pin number to find position for

Returns:

Absolute pin position in schematic coordinates, or None if pin not found

get_property(name: str, default: str | None = None) str | None[source]

Get property value by name.

Parameters:
  • name – Property name

  • default – Default value if property doesn’t exist

Returns:

Property value or default

get_property_effects(property_name: str) Dict[str, Any][source]

Get text effects for a component property.

Returns a dictionary with all text effects for the specified property (Reference, Value, Footprint, etc.), including position, rotation, font properties, color, justification, and visibility.

Parameters:

property_name – Property name (e.g., β€œReference”, β€œValue”, β€œFootprint”)

Returns:

{

β€˜position’: (x, y), # Position relative to component β€˜rotation’: float, # Rotation in degrees β€˜font_face’: str, # Font family name (or None for default) β€˜font_size’: (h, w), # Font size (height, width) in mm β€˜font_thickness’: float, # Font line thickness (or None) β€˜bold’: bool, # Bold flag β€˜italic’: bool, # Italic flag β€˜color’: (r, g, b, a), # RGBA color (or None) β€˜justify_h’: str, # Horizontal justification (or None) β€˜justify_v’: str, # Vertical justification (or None) β€˜visible’: bool, # Visibility (True = visible, False = hidden)

}

Return type:

Dictionary with effect properties

Raises:

ValueError – If property doesn’t exist

Example

>>> r1 = sch.components.get("R1")
>>> effects = r1.get_property_effects("Reference")
>>> print(f"Font size: {effects['font_size']}")
>>> print(f"Bold: {effects['bold']}")
get_symbol_definition() SymbolDefinition | None[source]

Get the symbol definition from library cache.

Returns:

SymbolDefinition if found, None otherwise

property hidden_properties: set[str]

Set of property names that have (hide yes) flag.

property in_bom: bool

Whether component appears in bill of materials.

property lib_id: str

R’).

Type:

Library identifier (e.g., β€˜Device

property library: str

R’).

Type:

Library name (e.g., β€˜Device’ from β€˜Device

list_pins() List[Dict[str, Any]][source]

List all pins for this component.

Returns:

  • number: Pin number (str)

  • name: Pin name (str)

  • type: Pin electrical type (str)

  • position: Absolute pin position (Point)

Return type:

List of pin dictionaries with keys

Example

>>> comp = sch.components.get("U1")
>>> pins = comp.list_pins()
>>> for pin in pins:
...     print(f"Pin {pin['number']}: {pin['name']} ({pin['type']})")
Pin 1: GND (POWER_IN)
Pin 2: 3V3 (POWER_IN)
move(x: float, y: float)[source]

Move component to absolute position.

Parameters:
  • x – X coordinate in mm

  • y – Y coordinate in mm

property on_board: bool

Whether component appears on PCB.

property pin_uuids: Dict[str, str]

Dictionary mapping pin numbers to their UUIDs.

property pins: List[SchematicPin]

List of component pins.

property position: Point

Component position in schematic (mm).

property properties: Dict[str, str]

Dictionary of all component properties.

property reference: str

Component reference designator (e.g., β€˜R1’, β€˜U2’).

remove_property(name: str) bool[source]

Remove property by name.

Parameters:

name – Property name to remove

Returns:

True if property was removed, False if it didn’t exist

rotate(angle: float)[source]

Rotate component by angle (cumulative).

Parameters:

angle – Rotation angle in degrees (will be normalized to 0/90/180/270)

property rotation: float

Component rotation in degrees (0, 90, 180, or 270).

set_property(name: str, value: str)[source]

Set property value with validation.

Parameters:
  • name – Property name

  • value – Property value

Raises:

ValidationError – If name or value are not strings

set_property_effects(property_name: str, effects: Dict[str, Any]) None[source]

Set text effects for a component property.

Updates text effects for the specified property. Only provided properties are updated - existing properties not specified in effects are preserved.

Parameters:
  • property_name – Property name (e.g., β€œReference”, β€œValue”, β€œFootprint”)

  • effects – Dictionary with effect updates (partial updates supported)

Raises:

ValueError – If property doesn’t exist

Example

>>> r1 = sch.components.get("R1")
>>> # Make Reference bold and larger
>>> r1.set_property_effects("Reference", {
...     "bold": True,
...     "font_size": (2.0, 2.0)
... })
>>>
>>> # Hide Footprint property
>>> r1.set_property_effects("Footprint", {"visible": False})
show_pins() None[source]

Display pin information in readable table format.

Prints a formatted table showing pin numbers, names, and types for all pins on this component. Useful for interactive exploration and debugging.

Example

>>> comp = sch.components.get("U1")
>>> comp.show_pins()

Pins for U1 (RF_Module:ESP32-WROOM-32): Pin# Name Type β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”- 1 GND POWER_IN 2 3V3 POWER_IN 3 EN INPUT …

property symbol_name: str

R’).

Type:

Symbol name within library (e.g., β€˜R’ from β€˜Device

to_dict() Dict[str, Any][source]

Convert component to dictionary representation.

Returns:

Dictionary with component data

translate(dx: float, dy: float)[source]

Translate component by offset.

Parameters:
  • dx – X offset in mm

  • dy – Y offset in mm

update_from_library() bool[source]

Update component pins and metadata from library definition.

Returns:

True if update successful, False if symbol not found

property uuid: str

Component UUID (read-only).

validate() List[ValidationIssue][source]

Validate this component.

Returns:

List of validation issues (empty if valid)

property value: str

Component value (e.g., β€˜10k’, β€˜100nF’).

class kicad_sch_api.collections.components.ComponentCollection(components: List[SchematicSymbol] | None = None, parent_schematic=None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Bases: BaseCollection[Component]

Collection class for efficient component management using IndexRegistry.

Provides fast lookup, filtering, and bulk operations with lazy index rebuilding and batch mode support. Uses centralized IndexRegistry for managing all indexes (UUID, reference, lib_id, value).

__contains__(item: str | Component) bool[source]

Check if reference, UUID, or component exists in collection.

Parameters:

item – Reference string, UUID string, or Component instance

Returns:

True if item exists, False otherwise

__getitem__(key: int | str) Component[source]

Get component by index, UUID, or reference.

Parameters:

key – Integer index, UUID string, or reference string

Returns:

Component at the specified location

Raises:
__init__(components: List[SchematicSymbol] | None = None, parent_schematic=None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Initialize component collection.

Parameters:
  • components – Initial list of component data

  • parent_schematic – Reference to parent Schematic (for hierarchy context)

  • validation_level – Validation level for operations

add(lib_id: str, reference: str | None = None, value: str = '', position: Point | Tuple[float, float] | None = None, footprint: str | None = None, unit: int = 1, add_all_units: bool = False, unit_spacing: float = 25.4, rotation: float = 0.0, component_uuid: str | None = None, grid_units: bool | None = None, grid_size: float | None = None, **properties) Component | MultiUnitComponentGroup[source]

Add a new component to the schematic.

Parameters:
  • lib_id – Library identifier (e.g., β€œDevice:R”)

  • reference – Component reference (auto-generated if None)

  • value – Component value

  • position – Component position in mm (or grid units if grid_units=True)

  • footprint – Component footprint

  • unit – Unit number for multi-unit components (1-based, default: 1)

  • add_all_units – If True, add all units with automatic layout (default: False)

  • unit_spacing – Horizontal spacing between units in mm (default: 25.4mm = 1 inch)

  • rotation – Component rotation in degrees (0, 90, 180, 270)

  • component_uuid – Specific UUID for component (auto-generated if None)

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size (default 1.27mm)

  • **properties – Additional component properties

Returns:

Component if adding single unit, MultiUnitComponentGroup if add_all_units=True

Raises:
  • ValidationError – If component data is invalid

  • LibraryError – If symbol library not found

Examples

# Single unit (default behavior) sch.components.add(β€˜Device:R’, β€˜R1’, β€˜10k’, position=(25.4, 50.8))

# Multi-unit automatic (all units with one call) group = sch.components.add(β€˜Amplifier_Operational:TL072’, β€˜U1’, β€˜TL072’,

position=(100, 100), add_all_units=True)

# Multi-unit manual (add each unit individually) sch.components.add(β€˜Amplifier_Operational:TL072’, β€˜U1’, β€˜TL072’,

position=(100, 100), unit=1)

sch.components.add(β€˜Amplifier_Operational:TL072’, β€˜U1’, β€˜TL072’,

position=(150, 100), unit=2)

add_ic(lib_id: str, reference_prefix: str, position: Point | Tuple[float, float] | None = None, value: str = '', footprint: str | None = None, layout_style: str = 'vertical', **properties) ICManager[source]

Add a multi-unit IC with automatic unit placement.

Parameters:
  • lib_id – Library identifier for the IC (e.g., β€œ74xx:7400”)

  • reference_prefix – Base reference (e.g., β€œU1” β†’ U1A, U1B, etc.)

  • position – Base position for auto-layout (auto-placed if None)

  • value – IC value (defaults to symbol name)

  • footprint – IC footprint

  • layout_style – Layout algorithm (β€œvertical”, β€œgrid”, β€œfunctional”)

  • **properties – Common properties for all units

Returns:

ICManager object for position overrides and management

Example

ic = sch.components.add_ic(β€œ74xx:7400”, β€œU1”, position=(100, 100)) ic.place_unit(1, position=(150, 80)) # Override Gate A position

add_with_pin_at(lib_id: str, pin_number: str, pin_position: Point | Tuple[float, float], reference: str | None = None, value: str = '', rotation: float = 0.0, footprint: str | None = None, unit: int = 1, component_uuid: str | None = None, **properties) Component[source]

Add component positioned by a specific pin location.

Instead of specifying the component’s center position, this method allows you to specify where a particular pin should be placed. This is extremely useful for aligning components in horizontal signal flows without manual offset calculations.

Parameters:
  • lib_id – Library identifier (e.g., β€œDevice:R”, β€œDevice:C”)

  • pin_number – Pin number to position (e.g., β€œ1”, β€œ2”)

  • pin_position – Desired position for the specified pin

  • reference – Component reference (auto-generated if None)

  • value – Component value

  • rotation – Component rotation in degrees (0, 90, 180, 270)

  • footprint – Component footprint

  • unit – Unit number for multi-unit components (1-based)

  • component_uuid – Specific UUID for component (auto-generated if None)

  • **properties – Additional component properties

Returns:

Newly created Component with the specified pin at pin_position

Raises:
  • ValidationError – If component data is invalid

  • LibraryError – If symbol library not found

  • ValueError – If pin_number doesn’t exist in the component

Example

# Place resistor with pin 2 at (150, 100) r1 = sch.components.add_with_pin_at(

lib_id=”Device:R”, pin_number=”2”, pin_position=(150, 100), value=”10k”

)

# Place capacitor with pin 1 aligned on same horizontal line c1 = sch.components.add_with_pin_at(

lib_id=”Device:C”, pin_number=”1”, pin_position=(200, 100), # Same Y as resistor pin 2 value=”100nF”

)

bulk_update(criteria: Dict[str, Any], updates: Dict[str, Any]) int[source]

Update multiple components matching criteria.

Parameters:
  • criteria – Filter criteria (same as filter method)

  • updates – Dictionary of property updates

Returns:

Number of components updated

Example

# Update all 10k resistors to 1% tolerance count = sch.components.bulk_update(

criteria={β€˜value’: β€˜10k’}, updates={β€˜properties’: {β€˜Tolerance’: β€˜1%’}}

)

filter(**criteria) List[Component][source]

Filter components by various criteria.

Supported criteria:

lib_id: Filter by library ID (exact match) value: Filter by value (exact match) value_pattern: Filter by value pattern (contains) reference_pattern: Filter by reference pattern (regex) footprint: Filter by footprint (exact match) in_area: Filter by area (tuple of (x1, y1, x2, y2)) has_property: Filter components that have a specific property

Parameters:

**criteria – Filter criteria

Returns:

List of matching components

filter_by_type(component_type: str) List[Component][source]

Filter components by type prefix.

Parameters:

component_type – Type prefix (e.g., β€˜R’ for resistors, β€˜C’ for capacitors)

Returns:

List of matching components

find_pins_by_name(reference: str, name_pattern: str, case_sensitive: bool = False) List[str] | None[source]

Find pin numbers matching a name pattern.

Supports both exact matches and wildcard patterns (e.g., β€œCLK*”, β€œIN”). By default, matching is case-insensitive for maximum flexibility.

Parameters:
  • reference – Component reference designator (e.g., β€œR1”, β€œU2”)

  • name_pattern – Name pattern to search for (e.g., β€œVCC”, β€œCLK”, β€œOUT”, β€œCLK*”, β€œIN”)

  • case_sensitive – If False (default), matching is case-insensitive

Returns:

List of matching pin numbers (e.g., [β€œ1”, β€œ2”]), or None if component not found

Raises:

ValueError – If name_pattern is empty

Example

# Find all clock pins pins = sch.components.find_pins_by_name(β€œU1”, β€œCLK*”) # Returns: [β€œ5”, β€œ10”] (whatever the clock pins are numbered)

# Find power pins pins = sch.components.find_pins_by_name(β€œU1”, β€œVCC”) # Returns: [β€œ1”, β€œ20”] for a common IC

find_pins_by_type(reference: str, pin_type: str | PinType) List[str] | None[source]

Find pin numbers by electrical type.

Returns all pins of a specific electrical type (e.g., all inputs, all power pins).

Parameters:
  • reference – Component reference designator (e.g., β€œR1”, β€œU2”)

  • pin_type – Electrical type filter. Can be: - String: β€œinput”, β€œoutput”, β€œpassive”, β€œpower_in”, β€œpower_out”, etc. - PinType enum value

Returns:

List of matching pin numbers, or None if component not found

Example

# Find all input pins pins = sch.components.find_pins_by_type(β€œU1”, β€œinput”) # Returns: [β€œ1”, β€œ2”, β€œ3”]

# Find all power pins pins = sch.components.find_pins_by_type(β€œU1”, β€œpower_in”) # Returns: [β€œ20”, β€œ40”] for a common IC

get(reference: str) Component | None[source]

Get component by reference designator.

Parameters:

reference – Component reference (e.g., β€œR1”)

Returns:

Component if found, None otherwise. If multiple components have the same reference (e.g., multi-unit components), returns the first one.

get_by_uuid(component_uuid: str) Component | None[source]

Get component by UUID.

Parameters:

component_uuid – Component UUID

Returns:

Component if found, None otherwise

get_pins_info(reference: str) List[PinInfo] | None[source]

Get comprehensive pin information for a component.

Returns all pins for the specified component with complete metadata including electrical type, shape, absolute position (accounting for rotation and mirroring), and orientation.

Parameters:

reference – Component reference designator (e.g., β€œR1”, β€œU2”)

Returns:

List of PinInfo objects with complete pin metadata, or None if component not found

Raises:

LibraryError – If component’s symbol library is not available

Example

pins = sch.components.get_pins_info(β€œU1”) if pins:

for pin in pins:

print(f”Pin {pin.number}: {pin.name} @ {pin.position}”) print(f” Electrical type: {pin.electrical_type.value}”) print(f” Shape: {pin.shape.value}”)

get_statistics() Dict[str, Any][source]

Get collection statistics.

Returns:

Dictionary with component statistics

in_area(x1: float, y1: float, x2: float, y2: float) List[Component][source]

Get components within rectangular area.

Parameters:
  • x1 – Top-left corner

  • y1 – Top-left corner

  • x2 – Bottom-right corner

  • y2 – Bottom-right corner

Returns:

List of components in area

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified (compatibility).

near_point(point: Point | Tuple[float, float], radius: float) List[Component][source]

Get components within radius of a point.

Parameters:
  • point – Center point (Point or (x, y) tuple)

  • radius – Search radius in mm

Returns:

List of components within radius

remove(reference: str) bool[source]

Remove component by reference designator.

Parameters:

reference – Component reference to remove (e.g., β€œR1”)

Returns:

True if component was removed, False if not found

Raises:

TypeError – If reference is not a string

remove_by_uuid(component_uuid: str) bool[source]

Remove component by UUID.

Parameters:

component_uuid – Component UUID to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If UUID is not a string

remove_component(component: Component) bool[source]

Remove component by component object.

Parameters:

component – Component object to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If component is not a Component instance

sort_by_position(by_x: bool = True)[source]

Sort components by position (in-place).

Parameters:

by_x – If True, sort by X then Y; if False, sort by Y then X

sort_by_reference()[source]

Sort components by reference designator (in-place).

validate_all() List[ValidationIssue][source]

Validate all components in collection.

Returns:

List of validation issues found

Wire Collection

Enhanced wire management with IndexRegistry integration.

Provides WireCollection using BaseCollection infrastructure with endpoint indexing and wire geometry queries.

class kicad_sch_api.collections.wires.WireCollection(wires: List[Wire] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Bases: BaseCollection[Wire]

Wire collection with endpoint indexing and geometry queries.

Inherits from BaseCollection for UUID indexing and adds wire-specific functionality for endpoint queries and wire type filtering.

Features: - Fast UUID lookup via IndexRegistry - Multi-point wire support - Endpoint-based queries - Horizontal/vertical wire detection - Lazy index rebuilding - Batch mode support

__init__(wires: List[Wire] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Initialize wire collection.

Parameters:
  • wires – Initial list of wires

  • validation_level – Validation level for operations

add(start: Point | Tuple[float, float] | None = None, end: Point | Tuple[float, float] | None = None, points: List[Point | Tuple[float, float]] | None = None, wire_type: WireType = WireType.WIRE, stroke_width: float = 0.0, uuid: str | None = None) str[source]

Add a wire to the collection.

Parameters:
  • start – Start point (for simple wires)

  • end – End point (for simple wires)

  • points – List of points (for multi-point wires)

  • wire_type – Wire type (wire or bus)

  • stroke_width – Line width

  • uuid – Optional UUID (auto-generated if not provided)

Returns:

UUID of the created wire

Raises:
  • ValueError – If neither start/end nor points are provided

  • ValueError – If UUID already exists

get_at_point(point: Point | Tuple[float, float], tolerance: float = 0.01) List[Wire][source]

Find all wires that pass through or near a point.

Parameters:
  • point – Point to search for

  • tolerance – Distance tolerance for matching

Returns:

List of wires passing through the point

get_by_endpoint(point: Point | Tuple[float, float], tolerance: float = 0.01) List[Wire][source]

Find all wires with an endpoint near a given point.

Parameters:
  • point – Point to search for

  • tolerance – Distance tolerance for matching

Returns:

List of wires with endpoint near the point

get_by_type(wire_type: WireType) List[Wire][source]

Get all wires of a specific type.

Parameters:

wire_type – Wire type to filter by

Returns:

List of wires matching the type

get_horizontal() List[Wire][source]

Get all horizontal wires (Y coordinates equal).

Returns:

List of horizontal wires

get_statistics() Dict[str, Any][source]

Get wire collection statistics.

Returns:

Dictionary with wire statistics

get_vertical() List[Wire][source]

Get all vertical wires (X coordinates equal).

Returns:

List of vertical wires

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified (compatibility).

Label Collection

Enhanced label management with IndexRegistry integration.

Provides LabelElement wrapper and LabelCollection using BaseCollection infrastructure with text indexing and position-based queries.

class kicad_sch_api.collections.labels.LabelCollection(labels: List[Label] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Bases: BaseCollection[LabelElement]

Label collection with text indexing and position queries.

Inherits from BaseCollection for UUID indexing and adds label-specific functionality including text-based searches and filtering.

Features: - Fast UUID lookup via IndexRegistry - Text-based label indexing - Position-based queries - Lazy index rebuilding - Batch mode support

__init__(labels: List[Label] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Initialize label collection.

Parameters:
  • labels – Initial list of label data

  • validation_level – Validation level for operations

add(text: str, position: Point | Tuple[float, float], rotation: float = 0.0, size: float = 1.27, justify_h: str = 'left', justify_v: str = 'bottom', uuid: str | None = None) LabelElement[source]

Add a label to the collection.

Parameters:
  • text – Label text (net name)

  • position – Label position

  • rotation – Label rotation in degrees

  • size – Text size

  • justify_h – Horizontal justification (β€œleft”, β€œright”, β€œcenter”)

  • justify_v – Vertical justification (β€œtop”, β€œbottom”, β€œcenter”)

  • uuid – Optional UUID (auto-generated if not provided)

Returns:

LabelElement wrapper for the created label

Raises:

ValueError – If UUID already exists or text is empty

filter_by_text_pattern(pattern: str) List[LabelElement][source]

Find labels with text containing a pattern.

Parameters:

pattern – Text pattern to search for (case-insensitive)

Returns:

List of labels with matching text

get_at_position(position: Point | Tuple[float, float], tolerance: float = 0.01) LabelElement | None[source]

Find label at or near a specific position.

Parameters:
  • position – Position to search

  • tolerance – Distance tolerance for matching

Returns:

Label if found, None otherwise

get_by_text(text: str) List[LabelElement][source]

Find all labels with specific text.

Parameters:

text – Text to search for

Returns:

List of labels with matching text

get_near_point(point: Point | Tuple[float, float], radius: float) List[LabelElement][source]

Find all labels within radius of a point.

Parameters:
  • point – Center point

  • radius – Search radius

Returns:

List of labels within radius

get_statistics() Dict[str, Any][source]

Get label collection statistics.

Returns:

Dictionary with label statistics

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified (compatibility).

remove(uuid: str) bool[source]

Remove label by UUID.

Parameters:

uuid – Label UUID to remove

Returns:

True if label was removed, False if not found

validate_all() List[ValidationIssue][source]

Validate all labels in collection.

Returns:

List of validation issues found

class kicad_sch_api.collections.labels.LabelElement(label_data: Label, parent_collection: LabelCollection)[source]

Bases: object

Enhanced wrapper for schematic label elements.

Provides intuitive access to label properties and operations while maintaining exact format preservation. All property modifications automatically notify the parent collection.

__init__(label_data: Label, parent_collection: LabelCollection)[source]

Initialize label element wrapper.

Parameters:
  • label_data – Underlying label data

  • parent_collection – Parent collection for modification tracking

__repr__() str[source]

Detailed representation for debugging.

__str__() str[source]

String representation for display.

move(x: float, y: float)[source]

Move label to absolute position.

property position: Point

Label position in schematic.

rotate_by(angle: float)[source]

Rotate label by angle (cumulative).

property rotation: float

Label rotation in degrees.

property size: float

Label text size.

property text: str

Label text (net name).

to_dict() Dict[str, Any][source]

Convert label to dictionary representation.

Returns:

Dictionary with label data

translate(dx: float, dy: float)[source]

Translate label by offset.

property uuid: str

Label element UUID (read-only).

validate() List[ValidationIssue][source]

Validate this label element.

Returns:

List of validation issues (empty if valid)

Junction Collection

Enhanced junction management with IndexRegistry integration.

Provides JunctionCollection using BaseCollection infrastructure with position-based queries and validation.

class kicad_sch_api.collections.junctions.JunctionCollection(junctions: List[Junction] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Bases: BaseCollection[Junction]

Junction collection with position-based queries.

Inherits from BaseCollection for UUID indexing and adds junction-specific position-based search capabilities.

Features: - Fast UUID lookup via IndexRegistry - Position-based junction queries - Lazy index rebuilding - Batch mode support

__init__(junctions: List[Junction] | None = None, validation_level: ValidationLevel = ValidationLevel.NORMAL)[source]

Initialize junction collection.

Parameters:
  • junctions – Initial list of junctions

  • validation_level – Validation level for operations

add(position: Point | Tuple[float, float], diameter: float = 0, color: Tuple[int, int, int, int] = (0, 0, 0, 0), uuid: str | None = None, grid_units: bool | None = None, grid_size: float | None = None) str[source]

Add a junction to the collection.

Parameters:
  • position – Junction position in mm (or grid units if grid_units=True)

  • diameter – Junction diameter (0 is KiCAD default)

  • color – RGBA color tuple (0,0,0,0 is default)

  • uuid – Optional UUID (auto-generated if not provided)

  • grid_units – If True, interpret position as grid units; if None, use config.positioning.use_grid_units

  • grid_size – Grid size in mm; if None, use config.positioning.grid_size

Returns:

UUID of the created junction

Raises:

ValueError – If UUID already exists

get_at_position(position: Point | Tuple[float, float], tolerance: float = 0.01) Junction | None[source]

Find junction at or near a specific position.

Parameters:
  • position – Position to search

  • tolerance – Distance tolerance for matching

Returns:

Junction if found, None otherwise

get_by_point(point: Point | Tuple[float, float], tolerance: float = 0.01) List[Junction][source]

Find all junctions near a point.

Parameters:
  • point – Point to search near

  • tolerance – Distance tolerance

Returns:

List of junctions near the point

get_statistics() Dict[str, Any][source]

Get junction collection statistics.

Returns:

Dictionary with junction statistics

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified (compatibility).

Element Wrappers

Components

Enhanced component management for KiCAD schematics.

This module provides a modern, intuitive API for working with schematic components, featuring fast lookup, bulk operations, and advanced filtering capabilities.

class kicad_sch_api.core.components.Component(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Bases: object

Enhanced wrapper for schematic components with modern API.

Provides intuitive access to component properties, pins, and operations while maintaining exact format preservation for professional use.

__init__(symbol_data: SchematicSymbol, parent_collection: ComponentCollection)[source]

Initialize component wrapper.

Parameters:
  • symbol_data – Underlying symbol data

  • parent_collection – Parent collection for updates

__repr__() str[source]

Detailed representation.

__str__() str[source]

String representation.

copy_properties_from(other: Component)[source]

Copy all properties from another component.

property footprint: str | None

Component footprint.

get_pin(pin_number: str) SchematicPin | None[source]

Get pin by number.

get_pin_position(pin_number: str) Point | None[source]

Get absolute position of pin.

get_property(name: str, default: str | None = None) str | None[source]

Get property value by name.

get_symbol_definition() SymbolDefinition | None[source]

Get the symbol definition from library cache.

property in_bom: bool

Whether component appears in bill of materials.

property lib_id: str

R’).

Type:

Library ID (e.g., β€˜Device

property library: str

Library name.

list_pins() List[Dict[str, Any]][source]

List all pins for this component.

Returns:

  • number: Pin number (str)

  • name: Pin name (str)

  • type: Pin electrical type (str)

  • position: Absolute pin position (Point)

Return type:

List of pin dictionaries with keys

Example

>>> comp = sch.components.get("U1")
>>> pins = comp.list_pins()
>>> for pin in pins:
...     print(f"Pin {pin['number']}: {pin['name']} ({pin['type']})")
Pin 1: GND (POWER_IN)
Pin 2: 3V3 (POWER_IN)
move(x: float, y: float)[source]

Move component to new position.

property on_board: bool

Whether component appears on PCB.

property pin_uuids: Dict[str, str]

Dictionary mapping pin numbers to their UUIDs.

property pins: List[SchematicPin]

List of component pins.

property position: Point

Component position.

property properties: Dict[str, str]

Dictionary of all component properties.

property reference: str

Component reference (e.g., β€˜R1’).

remove_property(name: str) bool[source]

Remove property by name.

rotate(angle: float)[source]

Rotate component by angle (degrees).

property rotation: float

Component rotation in degrees.

set_property(name: str, value: str)[source]

Set property value with validation.

show_pins() None[source]

Display pin information in readable table format.

Prints a formatted table showing pin numbers, names, and types for all pins on this component. Useful for interactive exploration and debugging.

Example

>>> comp = sch.components.get("U1")
>>> comp.show_pins()

Pins for U1 (RF_Module:ESP32-WROOM-32): Pin# Name Type β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”- 1 GND POWER_IN 2 3V3 POWER_IN 3 EN INPUT …

property symbol_name: str

Symbol name within library.

to_dict() Dict[str, Any][source]

Convert component to dictionary representation.

translate(dx: float, dy: float)[source]

Translate component by offset.

update_from_library() bool[source]

Update component pins and metadata from library definition.

property uuid: str

Component UUID.

validate() List[ValidationIssue][source]

Validate this component.

property value: str

Component value (e.g., β€˜10k’).

class kicad_sch_api.core.components.ComponentCollection(components: List[SchematicSymbol] = None, parent_schematic=None)[source]

Bases: BaseCollection[Component]

Collection class for efficient component management.

Inherits from BaseCollection for standard operations and adds component-specific functionality including reference, lib_id, and value-based indexing.

Provides fast lookup, filtering, and bulk operations for schematic components. Optimized for schematics with hundreds or thousands of components.

__contains__(reference: str) bool[source]

Check if reference exists.

__getitem__(key: int | str) Component[source]

Get component by index, UUID, or reference.

Parameters:

key – Integer index, UUID string, or reference string

Returns:

Component at the specified location

Raises:
__init__(components: List[SchematicSymbol] = None, parent_schematic=None)[source]

Initialize component collection.

Parameters:
  • components – Initial list of component data

  • parent_schematic – Reference to parent Schematic object (for hierarchy context)

add(lib_id: str, reference: str | None = None, value: str = '', position: Point | Tuple[float, float] | None = None, footprint: str | None = None, unit: int = 1, rotation: float = 0.0, component_uuid: str | None = None, grid_units: bool = False, grid_size: float = 1.27, **properties) Component[source]

Add a new component to the schematic.

Parameters:
  • lib_id – Library identifier (e.g., β€œDevice:R”)

  • reference – Component reference (auto-generated if None)

  • value – Component value

  • position – Component position in mm (or grid units if grid_units=True)

  • footprint – Component footprint

  • unit – Unit number for multi-unit components (1-based)

  • rotation – Component rotation in degrees (0, 90, 180, 270)

  • component_uuid – Specific UUID for component (auto-generated if None)

  • grid_units – If True, interpret position as grid units instead of mm

  • grid_size – Grid size in mm (default 1.27mm = 50 mil KiCAD standard)

  • **properties – Additional component properties

Returns:

Newly created Component

Raises:
  • ValidationError – If component data is invalid

  • LibraryError – If the KiCAD symbol library is not found

Examples

# Position in millimeters (default) sch.components.add(β€˜Device:R’, β€˜R1’, β€˜10k’, position=(25.4, 50.8))

# Position in grid units (cleaner for parametric design) sch.components.add(β€˜Device:R’, β€˜R1’, β€˜10k’, position=(20, 40), grid_units=True)

add_ic(lib_id: str, reference_prefix: str, position: Point | Tuple[float, float] | None = None, value: str = '', footprint: str | None = None, layout_style: str = 'vertical', **properties) ICManager[source]

Add a multi-unit IC with automatic unit placement.

Parameters:
  • lib_id – Library identifier for the IC (e.g., β€œ74xx:7400”)

  • reference_prefix – Base reference (e.g., β€œU1” β†’ U1A, U1B, etc.)

  • position – Base position for auto-layout (auto-placed if None)

  • value – IC value (defaults to symbol name)

  • footprint – IC footprint

  • layout_style – Layout algorithm (β€œvertical”, β€œgrid”, β€œfunctional”)

  • **properties – Common properties for all units

Returns:

ICManager object for position overrides and management

Example

ic = sch.components.add_ic(β€œ74xx:7400”, β€œU1”, position=(100, 100)) ic.place_unit(1, position=(150, 80)) # Override Gate A position

bulk_update(criteria: Dict[str, Any], updates: Dict[str, Any]) int[source]

Update multiple components matching criteria.

Parameters:
  • criteria – Filter criteria (same as filter method)

  • updates – Dictionary of property updates

Returns:

Number of components updated

filter(**criteria) List[Component][source]

Filter components by various criteria.

Parameters:
  • lib_id – Filter by library ID

  • value – Filter by value (exact match)

  • value_pattern – Filter by value pattern (contains)

  • reference_pattern – Filter by reference pattern

  • footprint – Filter by footprint

  • in_area – Filter by area (tuple of (x1, y1, x2, y2))

Returns:

List of matching components

filter_by_type(component_type: str) List[Component][source]

Filter components by type (e.g., β€˜R’ for resistors).

get(reference: str) Component | None[source]

Get component by reference.

get_statistics() Dict[str, Any][source]

Get collection statistics.

in_area(x1: float, y1: float, x2: float, y2: float) List[Component][source]

Get components within rectangular area.

near_point(point: Point | Tuple[float, float], radius: float) List[Component][source]

Get components within radius of a point.

remove(reference: str) bool[source]

Remove component by reference.

Parameters:

reference – Component reference to remove (e.g., β€œR1”)

Returns:

True if component was removed, False if not found

Raises:

TypeError – If reference is not a string

Examples

sch.components.remove(β€œR1”) sch.components.remove(β€œC2”)

Note

For removing by UUID or component object, use remove_by_uuid() or remove_component() respectively. This maintains a clear, simple API contract.

remove_by_uuid(component_uuid: str) bool[source]

Remove component by UUID.

Parameters:

component_uuid – Component UUID to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If UUID is not a string

remove_component(component: Component) bool[source]

Remove component by component object.

Parameters:

component – Component object to remove

Returns:

True if component was removed, False if not found

Raises:

TypeError – If component is not a Component instance

Examples

comp = sch.components.get(β€œR1”) sch.components.remove_component(comp)

sort_by_position(by_x: bool = True)[source]

Sort components by position.

sort_by_reference()[source]

Sort components by reference designator.

validate_all() List[ValidationIssue][source]

Validate all components in collection.

Wires

Wire collection and management for KiCAD schematics.

This module provides enhanced wire management with performance optimization, bulk operations, and professional validation features.

class kicad_sch_api.core.wires.WireCollection(wires: List[Wire] | None = None)[source]

Bases: BaseCollection[Wire]

Professional wire collection with enhanced management features.

Inherits from BaseCollection for standard operations and adds wire-specific functionality.

Features: - Fast UUID-based lookup and indexing (inherited) - Bulk operations for performance (inherited) - Multi-point wire support - Validation and conflict detection - Junction management integration - Wire geometry queries (horizontal, vertical, by-point)

__init__(wires: List[Wire] | None = None) None[source]

Initialize wire collection.

Parameters:

wires – Initial list of wires

add(start: Point | Tuple[float, float] | None = None, end: Point | Tuple[float, float] | None = None, points: List[Point | Tuple[float, float]] | None = None, wire_type: WireType = WireType.WIRE, stroke_width: float = 0.0, uuid: str | None = None) str[source]

Add a wire to the collection.

Parameters:
  • start – Start point (for simple wires)

  • end – End point (for simple wires)

  • points – List of points (for multi-point wires)

  • wire_type – Wire type (wire or bus)

  • stroke_width – Line width

  • uuid – Optional UUID (auto-generated if not provided)

Returns:

UUID of the created wire

Raises:

ValueError – If neither start/end nor points are provided

get_by_point(point: Point | Tuple[float, float], tolerance: float | None = None) List[Wire][source]

Find wires that pass through or near a point.

Parameters:
  • point – Point to search near

  • tolerance – Distance tolerance (uses config default if None)

Returns:

List of wires near the point

get_horizontal_wires() List[Wire][source]

Get all horizontal wires.

get_statistics() Dict[str, Any][source]

Get wire collection statistics (extends base statistics).

get_vertical_wires() List[Wire][source]

Get all vertical wires.

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified.

Labels

Label element management for KiCAD schematics.

This module provides collection classes for managing label elements, featuring fast lookup, bulk operations, and validation.

class kicad_sch_api.core.labels.LabelCollection(labels: List[Label] = None)[source]

Bases: BaseCollection[LabelElement]

Collection class for efficient label element management.

Inherits from BaseCollection for standard operations and adds label-specific functionality including text-based indexing.

Provides fast lookup, filtering, and bulk operations for schematic label elements.

__bool__() bool[source]

Return True if collection has labels.

__init__(labels: List[Label] = None)[source]

Initialize label collection.

Parameters:

labels – Initial list of label data

add(text: str, position: Point | Tuple[float, float], rotation: float = 0.0, size: float = 1.27, label_uuid: str | None = None) LabelElement[source]

Add a new label element to the schematic.

Parameters:
  • text – Label text (net name)

  • position – Label position

  • rotation – Label rotation in degrees

  • size – Label text size

  • label_uuid – Specific UUID for label (auto-generated if None)

Returns:

Newly created LabelElement

Raises:

ValidationError – If label data is invalid

bulk_update(criteria: Callable[[LabelElement], bool], updates: Dict[str, Any])[source]

Update multiple labels matching criteria.

Parameters:
  • criteria – Function to select labels to update

  • updates – Dictionary of property updates

clear()[source]

Remove all labels from collection.

filter(predicate: Callable[[LabelElement], bool]) List[LabelElement][source]

Filter labels by predicate function.

Parameters:

predicate – Function that returns True for labels to include

Returns:

List of labels matching predicate

find_by_text(text: str, exact: bool = True) List[LabelElement][source]

Find labels by text.

Parameters:
  • text – Text to search for

  • exact – If True, exact match; if False, substring match

Returns:

List of matching label elements

get_by_text(text: str) List[LabelElement][source]

Get all labels with the given text.

remove(label_uuid: str) bool[source]

Remove label by UUID.

Parameters:

label_uuid – UUID of label to remove

Returns:

True if label was removed, False if not found

class kicad_sch_api.core.labels.LabelElement(label_data: Label, parent_collection: LabelCollection)[source]

Bases: object

Enhanced wrapper for schematic label elements with modern API.

Provides intuitive access to label properties and operations while maintaining exact format preservation.

__init__(label_data: Label, parent_collection: LabelCollection)[source]

Initialize label element wrapper.

Parameters:
  • label_data – Underlying label data

  • parent_collection – Parent collection for updates

__str__() str[source]

String representation.

property position: Point

Label position.

property rotation: float

Label rotation in degrees.

property size: float

Label text size.

property text: str

Label text (net name).

to_dict() Dict[str, Any][source]

Convert label element to dictionary representation.

property uuid: str

Label element UUID.

validate() List[ValidationIssue][source]

Validate this label element.

Junctions

Junction collection and management for KiCAD schematics.

This module provides enhanced junction management for wire intersections and connection points with performance optimization and validation.

class kicad_sch_api.core.junctions.JunctionCollection(junctions: List[Junction] | None = None)[source]

Bases: BaseCollection[Junction]

Professional junction collection with enhanced management features.

Inherits from BaseCollection for standard operations and adds junction-specific functionality.

Features: - Fast UUID-based lookup and indexing (inherited) - Position-based junction queries - Bulk operations for performance (inherited) - Validation and conflict detection

__init__(junctions: List[Junction] | None = None) None[source]

Initialize junction collection.

Parameters:

junctions – Initial list of junctions

add(position: Point | Tuple[float, float], diameter: float = 0, color: Tuple[int, int, int, int] = (0, 0, 0, 0), uuid: str | None = None, grid_units: bool = False, grid_size: float = 1.27) str[source]

Add a junction to the collection.

Parameters:
  • position – Junction position in mm (or grid units if grid_units=True)

  • diameter – Junction diameter (0 is KiCAD default)

  • color – RGBA color tuple (0,0,0,0 is default)

  • uuid – Optional UUID (auto-generated if not provided)

  • grid_units – If True, interpret position as grid units instead of mm

  • grid_size – Grid size in mm (default 1.27mm = 50 mil KiCAD standard)

Returns:

UUID of the created junction

Raises:

ValueError – If UUID already exists

get_at_position(position: Point | Tuple[float, float], tolerance: float = 0.01) Junction | None[source]

Find junction at or near a specific position.

Parameters:
  • position – Position to search

  • tolerance – Distance tolerance for matching

Returns:

Junction if found, None otherwise

get_by_point(point: Point | Tuple[float, float], tolerance: float = 0.01) List[Junction][source]

Find all junctions near a point.

Parameters:
  • point – Point to search near

  • tolerance – Distance tolerance

Returns:

List of junctions near the point

get_statistics() Dict[str, Any][source]

Get junction collection statistics (extends base statistics).

mark_saved() None[source]

Mark collection as saved (reset modified flag).

property modified: bool

Check if collection has been modified.

Texts

Text element management for KiCAD schematics.

This module provides collection classes for managing text elements, featuring fast lookup, bulk operations, and validation.

class kicad_sch_api.core.texts.TextCollection(texts: List[Text] = None)[source]

Bases: BaseCollection[TextElement]

Collection class for efficient text element management.

Inherits from BaseCollection for standard operations and adds text-specific functionality including content-based indexing.

Provides fast lookup, filtering, and bulk operations for schematic text elements.

__bool__() bool[source]

Return True if collection has texts.

__init__(texts: List[Text] = None)[source]

Initialize text collection.

Parameters:

texts – Initial list of text data

add(text: str, position: Point | Tuple[float, float], rotation: float = 0.0, size: float = 1.27, exclude_from_sim: bool = False, text_uuid: str | None = None, bold: bool = False, italic: bool = False, thickness: float | None = None, color: Tuple[int, int, int, float] | None = None, face: str | None = None) TextElement[source]

Add a new text element to the schematic.

Parameters:
  • text – Text content

  • position – Text position

  • rotation – Text rotation in degrees

  • size – Text size

  • exclude_from_sim – Whether to exclude from simulation

  • text_uuid – Specific UUID for text (auto-generated if None)

  • bold – Bold font flag

  • italic – Italic font flag

  • thickness – Stroke width (None = use default)

  • color – RGBA color tuple (None = use default)

  • face – Font face name (None = use default)

Returns:

Newly created TextElement

Raises:

ValidationError – If text data is invalid

bulk_update(criteria: Callable[[TextElement], bool], updates: Dict[str, Any])[source]

Update multiple texts matching criteria.

Parameters:
  • criteria – Function to select texts to update

  • updates – Dictionary of property updates

clear()[source]

Remove all texts from collection.

filter(predicate: Callable[[TextElement], bool]) List[TextElement][source]

Filter texts by predicate function (delegates to base class find).

Parameters:

predicate – Function that returns True for texts to include

Returns:

List of texts matching predicate

find_by_content(content: str, exact: bool = True) List[TextElement][source]

Find texts by content.

Parameters:
  • content – Content to search for

  • exact – If True, exact match; if False, substring match

Returns:

List of matching text elements

remove(text_uuid: str) bool[source]

Remove text by UUID.

Parameters:

text_uuid – UUID of text to remove

Returns:

True if text was removed, False if not found

class kicad_sch_api.core.texts.TextElement(text_data: Text, parent_collection: TextCollection)[source]

Bases: object

Enhanced wrapper for schematic text elements with modern API.

Provides intuitive access to text properties and operations while maintaining exact format preservation.

__init__(text_data: Text, parent_collection: TextCollection)[source]

Initialize text element wrapper.

Parameters:
  • text_data – Underlying text data

  • parent_collection – Parent collection for updates

__str__() str[source]

String representation.

property bold: bool

Text bold flag.

property color: Tuple[int, int, int, float] | None

Text color (RGBA).

property exclude_from_sim: bool

Whether text is excluded from simulation.

property face: str | None

Font face name.

property italic: bool

Text italic flag.

property position: Point

Text position.

property rotation: float

Text rotation in degrees.

property size: float

Text size.

property text: str

Text content.

property thickness: float | None

Text stroke thickness.

to_dict() Dict[str, Any][source]

Convert text element to dictionary representation.

property uuid: str

Text element UUID.

validate() List[ValidationIssue][source]

Validate this text element.

Data Types

Core data types for KiCAD schematic manipulation.

This module defines the fundamental data structures used throughout kicad-sch-api, providing a clean, type-safe interface for working with schematic elements.

class kicad_sch_api.core.types.BusEntry(uuid: str, position: Point, size: Point = None, rotation: int = 0, stroke_width: float = 0.0, stroke_type: str = 'default')[source]

Bases: object

Bus entry point connecting individual wires to buses.

__post_init__() None[source]

Initialize defaults and validate rotation.

position: Point
rotation: int = 0
size: Point = None
stroke_type: str = 'default'
stroke_width: float = 0.0
uuid: str
class kicad_sch_api.core.types.HierarchicalLabelShape(*values)[source]

Bases: Enum

Hierarchical label shapes/directions.

BIDIRECTIONAL = 'bidirectional'
INPUT = 'input'
OUTPUT = 'output'
PASSIVE = 'passive'
TRISTATE = 'tri_state'
UNSPECIFIED = 'unspecified'
class kicad_sch_api.core.types.Image(uuid: str, position: Point, data: str, scale: float = 1.0)[source]

Bases: object

Image element in schematic.

data: str
position: Point
scale: float = 1.0
uuid: str
class kicad_sch_api.core.types.Junction(uuid: str, position: Point, diameter: float = 0, color: Tuple[int, int, int, int] = (0, 0, 0, 0))[source]

Bases: object

Junction point where multiple wires meet.

color: Tuple[int, int, int, int] = (0, 0, 0, 0)
diameter: float = 0
position: Point
uuid: str
class kicad_sch_api.core.types.Label(uuid: str, position: Point, text: str, label_type: LabelType = LabelType.LOCAL, rotation: float = 0.0, size: float = 1.27, shape: HierarchicalLabelShape | None = None, justify_h: str = 'left', justify_v: str = 'bottom')[source]

Bases: object

Text label in schematic.

justify_h: str = 'left'
justify_v: str = 'bottom'
label_type: LabelType = 'label'
position: Point
rotation: float = 0.0
shape: HierarchicalLabelShape | None = None
size: float = 1.27
text: str
uuid: str
class kicad_sch_api.core.types.LabelType(*values)[source]

Bases: Enum

Label types in KiCAD schematics.

GLOBAL = 'global_label'
HIERARCHICAL = 'hierarchical_label'
LOCAL = 'label'
class kicad_sch_api.core.types.Net(name: str, components: ~typing.List[~typing.Tuple[str, str]] = <factory>, wires: ~typing.List[str] = <factory>, labels: ~typing.List[str] = <factory>)[source]

Bases: object

Electrical net connecting components.

add_connection(reference: str, pin: str) None[source]

Add component pin to net.

components: List[Tuple[str, str]]
labels: List[str]
name: str
remove_connection(reference: str, pin: str) None[source]

Remove component pin from net.

wires: List[str]
class kicad_sch_api.core.types.NoConnect(uuid: str, position: Point)[source]

Bases: object

No-connect symbol in schematic.

position: Point
uuid: str
class kicad_sch_api.core.types.PinInfo(number: str, name: str, position: Point, electrical_type: PinType = PinType.PASSIVE, shape: PinShape = PinShape.LINE, length: float = 2.54, orientation: float = 0.0, uuid: str = '')[source]

Bases: object

Complete pin information for a component pin.

This dataclass provides comprehensive pin metadata including position, electrical properties, and graphical representation. Positions are in schematic coordinates (absolute positions accounting for component rotation and mirroring).

__post_init__() None[source]

Validate and normalize pin information.

electrical_type: PinType = 'passive'
length: float = 2.54
name: str
number: str
orientation: float = 0.0
position: Point
shape: PinShape = 'line'
to_dict() Dict[str, Any][source]

Convert pin info to dictionary representation.

uuid: str = ''
class kicad_sch_api.core.types.PinShape(*values)[source]

Bases: Enum

KiCAD pin graphical shapes.

CLOCK = 'clock'
CLOCK_LOW = 'clock_low'
EDGE_CLOCK_HIGH = 'edge_clock_high'
INPUT_LOW = 'input_low'
INVERTED = 'inverted'
INVERTED_CLOCK = 'inverted_clock'
LINE = 'line'
NON_LOGIC = 'non_logic'
OUTPUT_LOW = 'output_low'
class kicad_sch_api.core.types.PinType(*values)[source]

Bases: Enum

KiCAD pin electrical types.

BIDIRECTIONAL = 'bidirectional'
FREE = 'free'
INPUT = 'input'
NO_CONNECT = 'no_connect'
OPEN_COLLECTOR = 'open_collector'
OPEN_EMITTER = 'open_emitter'
OUTPUT = 'output'
PASSIVE = 'passive'
POWER_IN = 'power_in'
POWER_OUT = 'power_out'
TRISTATE = 'tri_state'
UNSPECIFIED = 'unspecified'
class kicad_sch_api.core.types.Point(x: float, y: float)[source]

Bases: object

2D point with x,y coordinates in mm.

distance_to(other: Point) float[source]

Calculate distance to another point.

offset(dx: float, dy: float) Point[source]

Create new point offset by dx, dy.

x: float
y: float
class kicad_sch_api.core.types.Rectangle(top_left: Point, bottom_right: Point)[source]

Bases: object

Rectangle defined by two corner points.

bottom_right: Point
property center: Point

Rectangle center point.

contains(point: Point) bool[source]

Check if point is inside rectangle.

property height: float

Rectangle height.

top_left: Point
property width: float

Rectangle width.

class kicad_sch_api.core.types.Schematic(version: str | None = None, generator: str | None = None, uuid: str | None = None, title_block: ~kicad_sch_api.core.types.TitleBlock = <factory>, components: ~typing.List[~kicad_sch_api.core.types.SchematicSymbol] = <factory>, wires: ~typing.List[~kicad_sch_api.core.types.Wire] = <factory>, junctions: ~typing.List[~kicad_sch_api.core.types.Junction] = <factory>, labels: ~typing.List[~kicad_sch_api.core.types.Label] = <factory>, nets: ~typing.List[~kicad_sch_api.core.types.Net] = <factory>, sheets: ~typing.List[~kicad_sch_api.core.types.Sheet] = <factory>, rectangles: ~typing.List[~kicad_sch_api.core.types.SchematicRectangle] = <factory>, lib_symbols: ~typing.Dict[str, ~typing.Any] = <factory>)[source]

Bases: object

Complete schematic data structure.

component_count() int[source]

Get total number of components.

components: List[SchematicSymbol]
connection_count() int[source]

Get total number of connections (wires + net connections).

generator: str | None = None
get_component(reference: str) SchematicSymbol | None[source]

Get component by reference.

get_net(name: str) Net | None[source]

Get net by name.

junctions: List[Junction]
labels: List[Label]
lib_symbols: Dict[str, Any]
nets: List[Net]
rectangles: List[SchematicRectangle]
sheets: List[Sheet]
title_block: TitleBlock
uuid: str | None = None
version: str | None = None
wires: List[Wire]
class kicad_sch_api.core.types.SchematicPin(number: str, name: str, position: Point, pin_type: PinType = PinType.PASSIVE, pin_shape: PinShape = PinShape.LINE, length: float = 2.54, rotation: float = 0.0)[source]

Bases: object

Pin definition for schematic symbols.

length: float = 2.54
name: str
number: str
pin_shape: PinShape = 'line'
pin_type: PinType = 'passive'
position: Point
rotation: float = 0.0
class kicad_sch_api.core.types.SchematicRectangle(uuid: str, start: Point, end: Point, stroke_width: float = 0.0, stroke_type: str = 'default', fill_type: str = 'none')[source]

Bases: object

Graphical rectangle element in schematic.

property center: Point

Rectangle center point.

end: Point
fill_type: str = 'none'
property height: float

Rectangle height.

start: Point
stroke_type: str = 'default'
stroke_width: float = 0.0
uuid: str
property width: float

Rectangle width.

class kicad_sch_api.core.types.SchematicSymbol(uuid: str, lib_id: str, position: ~kicad_sch_api.core.types.Point, reference: str, value: str = '', footprint: str | None = None, properties: ~typing.Dict[str, str] = <factory>, pins: ~typing.List[~kicad_sch_api.core.types.SchematicPin] = <factory>, pin_uuids: ~typing.Dict[str, str] = <factory>, hidden_properties: set[str] = <factory>, rotation: float = 0.0, in_bom: bool = True, on_board: bool = True, fields_autoplaced: bool = False, unit: int = 1, instances: ~typing.List[~kicad_sch_api.core.types.SymbolInstance] = <factory>)[source]

Bases: object

Component symbol in a schematic.

add_properties(props: Dict[str, str], hidden: bool = False) None[source]

Add or update multiple properties with same visibility setting.

Convenience method for bulk property operations. All properties will have the same visibility state.

Parameters:
  • props – Dictionary of property name/value pairs

  • hidden – If True, all properties will be hidden. If False, all will be visible. Default: False

Example

>>> component.add_properties({
...     "MPN": "RC0603FR-0710KL",
...     "Manufacturer": "Yageo",
...     "Supplier": "Digikey"
... }, hidden=True)
add_property(name: str, value: str, hidden: bool = False) None[source]

Add or update a component property with visibility control.

Sets the property value and manages its visibility state. If the property already exists, both value and visibility are updated.

Parameters:
  • name – Property name (e.g., β€œMPN”, β€œManufacturer”, β€œTolerance”)

  • value – Property value

  • hidden – If True, property will have (hide yes) flag in S-expression. If False, property will be visible on schematic. Default: False

Example

>>> component.add_property("MPN", "RC0603FR-0710KL", hidden=True)
>>> component.add_property("Tolerance", "1%", hidden=False)
fields_autoplaced: bool = False
footprint: str | None = None
get_pin(pin_number: str) SchematicPin | None[source]

Get pin by number.

get_pin_position(pin_number: str) Point | None[source]

Get absolute position of a pin with rotation transformation.

Parameters:

pin_number – Pin number to get position for

Returns:

Absolute position of the pin in schematic coordinates, or None if pin not found

Note

Applies standard 2D rotation matrix to transform pin position from symbol’s local coordinate system to schematic’s global coordinate system.

get_property_effects(property_name: str) Dict[str, Any][source]

Get text effects for a component property.

Extracts and parses the effects (font, position, rotation, color, etc.) from the property’s S-expression.

Parameters:

property_name – Name of property (β€œReference”, β€œValue”, β€œFootprint”, etc.)

Returns:

{

β€˜position’: (x, y), β€˜rotation’: float, β€˜font_face’: str or None, β€˜font_size’: (height, width), β€˜font_thickness’: float or None, β€˜bold’: bool, β€˜italic’: bool, β€˜color’: (r, g, b, a) or None, β€˜justify_h’: str or None, β€˜justify_v’: str or None, β€˜visible’: bool,

}

Return type:

Dictionary with effect properties

Raises:

ValueError – If property doesn’t exist

Example

>>> comp = sch.components[0]
>>> effects = comp.get_property_effects("Reference")
>>> print(effects['font_size'])
(1.27, 1.27)
>>> print(effects['bold'])
False
hidden_properties: set[str]
in_bom: bool = True
instances: List[SymbolInstance]
lib_id: str
property library: str

Extract library name from lib_id.

on_board: bool = True
pin_uuids: Dict[str, str]
pins: List[SchematicPin]
position: Point
properties: Dict[str, str]
reference: str
rotation: float = 0.0
set_property_effects(property_name: str, effects: Dict[str, Any]) None[source]

Set text effects for a component property.

Modifies the property’s text effects (font, position, rotation, color, etc.). Only specified effects are changed - others are preserved.

Parameters:
  • property_name – Name of property (β€œReference”, β€œValue”, β€œFootprint”, etc.)

  • effects –

    Dictionary with effect properties to change: {

    ’position’: (x, y), # Optional β€˜rotation’: float, # Optional β€˜font_face’: str, # Optional β€˜font_size’: (h, w), # Optional β€˜font_thickness’: float, # Optional β€˜bold’: bool, # Optional β€˜italic’: bool, # Optional β€˜color’: (r, g, b, a), # Optional β€˜justify_h’: str, # Optional (β€˜left’, β€˜right’, β€˜center’) β€˜justify_v’: str, # Optional (β€˜top’, β€˜bottom’) β€˜visible’: bool, # Optional

    }

Raises:

ValueError – If property doesn’t exist

Example

>>> comp = sch.components[0]
>>> # Make Reference bold and larger
>>> comp.set_property_effects("Reference", {
...     'bold': True,
...     'font_size': (2.0, 2.0)
... })
>>> # Hide Footprint
>>> comp.set_property_effects("Footprint", {'visible': False})
property symbol_name: str

Extract symbol name from lib_id.

unit: int = 1
uuid: str
value: str = ''
class kicad_sch_api.core.types.Sheet(uuid: str, position: ~kicad_sch_api.core.types.Point, size: ~kicad_sch_api.core.types.Point, name: str, filename: str, pins: ~typing.List[~kicad_sch_api.core.types.SheetPin] = <factory>, exclude_from_sim: bool = False, in_bom: bool = True, on_board: bool = True, dnp: bool = False, fields_autoplaced: bool = True, stroke_width: float = 0.1524, stroke_type: str = 'solid', fill_color: ~typing.Tuple[float, float, float, float] = (0, 0, 0, 0.0))[source]

Bases: object

Hierarchical sheet in schematic.

dnp: bool = False
exclude_from_sim: bool = False
fields_autoplaced: bool = True
filename: str
fill_color: Tuple[float, float, float, float] = (0, 0, 0, 0.0)
in_bom: bool = True
name: str
on_board: bool = True
pins: List[SheetPin]
position: Point
size: Point
stroke_type: str = 'solid'
stroke_width: float = 0.1524
uuid: str
class kicad_sch_api.core.types.SheetPin(uuid: str, name: str, position: Point, pin_type: PinType = PinType.BIDIRECTIONAL, size: float = 1.27)[source]

Bases: object

Pin on hierarchical sheet.

name: str
pin_type: PinType = 'bidirectional'
position: Point
size: float = 1.27
uuid: str
class kicad_sch_api.core.types.SymbolInfo(lib_id: str, name: str, library: str, reference_prefix: str, description: str, keywords: str, datasheet: str, unit_count: int, unit_names: Dict[int, str], pins: List[SchematicPin], power_symbol: bool)[source]

Bases: object

Symbol metadata from library cache for multi-unit component introspection.

Used by get_symbol_info() to query unit count, names, and other metadata before adding components programmatically.

datasheet: str
description: str
keywords: str
lib_id: str
library: str
name: str
pins: List[SchematicPin]
power_symbol: bool
reference_prefix: str
unit_count: int
unit_names: Dict[int, str]
class kicad_sch_api.core.types.SymbolInstance(path: str, reference: str, unit: int = 1, project: str = '')[source]

Bases: object

Instance of a symbol from library.

path: str
project: str = ''
reference: str
unit: int = 1
class kicad_sch_api.core.types.Text(uuid: str, position: Point, text: str, rotation: float = 0.0, size: float = 1.27, exclude_from_sim: bool = False, bold: bool = False, italic: bool = False, thickness: float | None = None, color: Tuple[int, int, int, float] | None = None, face: str | None = None)[source]

Bases: object

Free text element in schematic.

bold: bool = False
color: Tuple[int, int, int, float] | None = None
exclude_from_sim: bool = False
face: str | None = None
italic: bool = False
position: Point
rotation: float = 0.0
size: float = 1.27
text: str
thickness: float | None = None
uuid: str
class kicad_sch_api.core.types.TextBox(uuid: str, position: Point, size: Point, text: str, rotation: float = 0.0, font_size: float = 1.27, margins: Tuple[float, float, float, float] = (0.9525, 0.9525, 0.9525, 0.9525), stroke_width: float = 0.0, stroke_type: str = 'solid', fill_type: str = 'none', justify_horizontal: str = 'left', justify_vertical: str = 'top', exclude_from_sim: bool = False)[source]

Bases: object

Text box element with border in schematic.

exclude_from_sim: bool = False
fill_type: str = 'none'
font_size: float = 1.27
justify_horizontal: str = 'left'
justify_vertical: str = 'top'
margins: Tuple[float, float, float, float] = (0.9525, 0.9525, 0.9525, 0.9525)
position: Point
rotation: float = 0.0
size: Point
stroke_type: str = 'solid'
stroke_width: float = 0.0
text: str
uuid: str
class kicad_sch_api.core.types.TitleBlock(title: str = '', company: str = '', rev: str = '', date: str = '', size: str = 'A4', comments: ~typing.Dict[int, str] = <factory>)[source]

Bases: object

Title block information.

comments: Dict[int, str]
company: str = ''
date: str = ''
rev: str = ''
size: str = 'A4'
title: str = ''
class kicad_sch_api.core.types.Wire(uuid: str, points: List[Point], wire_type: WireType = WireType.WIRE, stroke_width: float = 0.0, stroke_type: str = 'default')[source]

Bases: object

Wire connection in schematic.

property end: Point

Last point of the wire.

classmethod from_start_end(uuid: str, start: Point, end: Point, **kwargs: Any) Wire[source]

Create wire from start and end points (convenience method).

is_horizontal() bool[source]

Check if wire is horizontal (only for simple wires).

is_simple() bool[source]

Check if wire is a simple 2-point wire.

is_vertical() bool[source]

Check if wire is vertical (only for simple wires).

property length: float

Total wire length (sum of all segments).

points: List[Point]
property start: Point

First point of the wire.

stroke_type: str = 'default'
stroke_width: float = 0.0
uuid: str
wire_type: WireType = 'wire'
class kicad_sch_api.core.types.WireType(*values)[source]

Bases: Enum

Wire types in KiCAD schematics.

BUS = 'bus'
WIRE = 'wire'
kicad_sch_api.core.types.point_from_dict_or_tuple(position: Point | Dict[str, float] | Tuple[float, float] | List[float] | Any) Point[source]

Convert various position formats to a Point object.

Supports multiple input formats for maximum flexibility: - Point: Returns as-is - Dict with β€˜x’ and β€˜y’ keys: Extracts and creates Point - Tuple/List with 2 elements: Creates Point from coordinates - Other: Returns as-is (assumes it’s already a Point-like object)

Parameters:

position – Position in any supported format

Returns:

Point object

Example

>>> point_from_dict_or_tuple({"x": 10, "y": 20})
Point(x=10.0, y=20.0)
>>> point_from_dict_or_tuple((10, 20))
Point(x=10.0, y=20.0)
>>> point_from_dict_or_tuple(Point(10, 20))
Point(x=10.0, y=20.0)

Configuration

Configuration constants and settings for KiCAD schematic API.

This module centralizes all magic numbers and configuration values to make them easily configurable and maintainable.

class kicad_sch_api.core.config.DefaultValues(project_name: str = 'untitled', stroke_width: float = 0.0, stroke_type: str = 'default', fill_type: str = 'none', font_size: float = 1.27, pin_name_size: float = 1.27, pin_number_size: float = 1.27)[source]

Bases: object

Default values for various operations.

fill_type: str = 'none'
font_size: float = 1.27
pin_name_size: float = 1.27
pin_number_size: float = 1.27
project_name: str = 'untitled'
stroke_type: str = 'default'
stroke_width: float = 0.0
class kicad_sch_api.core.config.FieldNames(version: str = 'version', generator: str = 'generator', generator_version: str = 'generator_version', uuid: str = 'uuid', paper: str = 'paper', at: str = 'at', xy: str = 'xy', pts: str = 'pts', start: str = 'start', end: str = 'end', mid: str = 'mid', center: str = 'center', radius: str = 'radius', stroke: str = 'stroke', fill: str = 'fill', width: str = 'width', type: str = 'type', color: str = 'color', font: str = 'font', size: str = 'size', effects: str = 'effects', pin: str = 'pin', property: str = 'property', symbol: str = 'symbol', lib_id: str = 'lib_id', polyline: str = 'polyline', arc: str = 'arc', circle: str = 'circle', rectangle: str = 'rectangle', bezier: str = 'bezier', wire: str = 'wire', junction: str = 'junction', no_connect: str = 'no_connect', label: str = 'label', sheet: str = 'sheet', sheet_instances: str = 'sheet_instances')[source]

Bases: object

Common S-expression field names to avoid typos.

arc: str = 'arc'
at: str = 'at'
bezier: str = 'bezier'
center: str = 'center'
circle: str = 'circle'
color: str = 'color'
effects: str = 'effects'
end: str = 'end'
fill: str = 'fill'
font: str = 'font'
generator: str = 'generator'
generator_version: str = 'generator_version'
junction: str = 'junction'
label: str = 'label'
lib_id: str = 'lib_id'
mid: str = 'mid'
no_connect: str = 'no_connect'
paper: str = 'paper'
pin: str = 'pin'
polyline: str = 'polyline'
property: str = 'property'
pts: str = 'pts'
radius: str = 'radius'
rectangle: str = 'rectangle'
sheet: str = 'sheet'
sheet_instances: str = 'sheet_instances'
size: str = 'size'
start: str = 'start'
stroke: str = 'stroke'
symbol: str = 'symbol'
type: str = 'type'
uuid: str = 'uuid'
version: str = 'version'
width: str = 'width'
wire: str = 'wire'
xy: str = 'xy'
class kicad_sch_api.core.config.FileFormatConstants(file_type: str = 'kicad_sch', generator_default: str = 'eeschema', version_default: str = '20250114', generator_version_default: str = '9.0')[source]

Bases: object

KiCAD file format identifiers and version strings.

file_type: str = 'kicad_sch'
generator_default: str = 'eeschema'
generator_version_default: str = '9.0'
version_default: str = '20250114'
class kicad_sch_api.core.config.GridSettings(standard_grid: float = 1.27, component_spacing: float = 2.54, unit_spacing: float = 12.7, power_offset: Tuple[float, float] = (25.4, 0.0))[source]

Bases: object

Standard KiCAD grid and spacing settings.

component_spacing: float = 2.54
power_offset: Tuple[float, float] = (25.4, 0.0)
standard_grid: float = 1.27
unit_spacing: float = 12.7
class kicad_sch_api.core.config.KiCADConfig[source]

Bases: object

Central configuration class for KiCAD schematic API.

get_property_position(property_name: str, component_pos: Tuple[float, float], offset_index: int = 0, component_rotation: float = 0) Tuple[float, float, float][source]

Calculate property position relative to component, accounting for component rotation.

Parameters:
  • property_name – Name of the property (Reference, Value, etc.)

  • component_pos – (x, y) position of component

  • offset_index – Stacking offset for multiple properties

  • component_rotation – Rotation of the component in degrees (0, 90, 180, 270)

Returns:

Tuple of (x, y, rotation) for the property

should_add_title_block(name: str) bool[source]

Determine if a schematic name should generate a title block.

class kicad_sch_api.core.config.PaperSizeConstants(default: str = 'A4', valid_sizes: ~typing.List[str] = <factory>)[source]

Bases: object

Standard paper size definitions.

default: str = 'A4'
valid_sizes: List[str]
class kicad_sch_api.core.config.PositioningSettings(use_grid_units: bool = False, grid_size: float = 1.27)[source]

Bases: object

Global positioning behavior settings.

grid_size: float = 1.27
use_grid_units: bool = False
class kicad_sch_api.core.config.PropertyOffsets(reference_x: float = 2.54, reference_y: float = -1.2701, value_x: float = 2.54, value_y: float = 1.2699, footprint_rotation: float = 90, hidden_property_offset: float = 1.27)[source]

Bases: object

Standard property positioning offsets relative to component position.

footprint_rotation: float = 90
hidden_property_offset: float = 1.27
reference_x: float = 2.54
reference_y: float = -1.2701
value_x: float = 2.54
value_y: float = 1.2699
class kicad_sch_api.core.config.SheetSettings(name_offset_y: float = -0.7116, file_offset_y: float = 0.5846, default_stroke_width: float = 0.1524, default_stroke_type: str = 'solid')[source]

Bases: object

Hierarchical sheet positioning settings.

default_stroke_type: str = 'solid'
default_stroke_width: float = 0.1524
file_offset_y: float = 0.5846
name_offset_y: float = -0.7116
class kicad_sch_api.core.config.ToleranceSettings(position_tolerance: float = 0.1, wire_segment_min: float = 0.001, coordinate_precision: float = 0.01)[source]

Bases: object

Tolerance values for various operations.

coordinate_precision: float = 0.01
position_tolerance: float = 0.1
wire_segment_min: float = 0.001

Parser & Formatter

Parser

S-expression parser for KiCAD schematic files.

This module provides robust parsing and writing capabilities for KiCAD’s S-expression format, with exact format preservation and enhanced error handling.

class kicad_sch_api.core.parser.SExpressionParser(preserve_format: bool = True)[source]

Bases: object

High-performance S-expression parser for KiCAD schematic files.

Features: - Exact format preservation - Enhanced error handling with detailed validation - Optimized for large schematics - Support for KiCAD 9 format

__init__(preserve_format: bool = True)[source]

Initialize the parser.

Parameters:

preserve_format – If True, preserve exact formatting when writing

dumps(data: Any, pretty: bool = True) str[source]

Convert S-expression data to string.

Parameters:
  • data – S-expression data structure

  • pretty – If True, format with proper indentation

Returns:

Formatted S-expression string

get_validation_issues() List[ValidationIssue][source]

Get list of validation issues from last parse operation.

parse_file(filepath: str | Path) Dict[str, Any][source]

Parse a KiCAD schematic file with comprehensive validation.

Parameters:

filepath – Path to the .kicad_sch file

Returns:

Parsed schematic data structure

Raises:
parse_string(content: str) Any[source]

Parse S-expression content from string.

Parameters:

content – S-expression string content

Returns:

Parsed S-expression data structure

Raises:

ValidationError – If parsing fails

property project_name

Get project name.

write_file(schematic_data: Dict[str, Any], filepath: str | Path)[source]

Write schematic data to file with exact format preservation.

Parameters:
  • schematic_data – Schematic data structure

  • filepath – Path to write to

Formatter

Exact formatting preservation for KiCAD schematic files.

This module provides precise S-expression formatting that matches KiCAD’s native output exactly, ensuring round-trip compatibility and professional output quality.

class kicad_sch_api.core.formatter.CompactFormatter[source]

Bases: ExactFormatter

Compact formatter for minimal output size.

class kicad_sch_api.core.formatter.DebugFormatter[source]

Bases: ExactFormatter

Debug formatter with extra spacing and comments.

format(data: Any) str[source]

Format with debug information.

class kicad_sch_api.core.formatter.ExactFormatter[source]

Bases: object

S-expression formatter that produces output identical to KiCAD’s native formatting.

This formatter ensures exact format preservation for professional schematic manipulation, matching KiCAD’s indentation, spacing, and quoting conventions precisely.

__init__()[source]

Initialize the formatter with KiCAD-specific rules.

format(data: Any) str[source]

Format S-expression data with exact KiCAD formatting.

Parameters:

data – S-expression data structure

Returns:

Formatted string matching KiCAD’s output exactly

format_preserving_write(new_data: Any, original_content: str) str[source]

Write new data while preserving as much original formatting as possible.

This method attempts to maintain the original file’s formatting style while incorporating changes from the new data structure.

Parameters:
  • new_data – New S-expression data to write

  • original_content – Original file content for format reference

Returns:

Formatted string with preserved styling where possible

class kicad_sch_api.core.formatter.FormatRule(inline: bool = False, max_inline_elements: int | None = None, quote_indices: Set[int] = None, custom_handler: Callable | None = None, indent_level: int = 1)[source]

Bases: object

Formatting rule for S-expression elements.

custom_handler: Callable | None = None
indent_level: int = 1
inline: bool = False
max_inline_elements: int | None = None
quote_indices: Set[int] = None

Element Parsers

Component symbol elements parser for KiCAD schematics.

Handles parsing and serialization of Component symbol elements.

class kicad_sch_api.parsers.elements.symbol_parser.SymbolParser[source]

Bases: BaseElementParser

Parser for Component symbol elements.

__init__()[source]

Initialize symbol parser.

Wire and connection element parsers for KiCAD schematics.

Handles parsing and serialization of connection elements: - Wire - Junction - No-connect

class kicad_sch_api.parsers.elements.wire_parser.WireParser[source]

Bases: BaseElementParser

Parser for wire and connection elements.

__init__()[source]

Initialize wire parser.

Label and hierarchical label elements parser for KiCAD schematics.

Handles parsing and serialization of Label and hierarchical label elements.

class kicad_sch_api.parsers.elements.label_parser.LabelParser[source]

Bases: BaseElementParser

Parser for Label and hierarchical label elements.

__init__()[source]

Initialize label parser.

Library Integration

Symbol Cache

High-performance symbol library cache for KiCAD schematic API.

This module provides intelligent caching and lookup functionality for KiCAD symbol libraries, significantly improving performance for applications that work with many components.

class kicad_sch_api.library.cache.LibraryStats(library_path: Path, symbol_count: int = 0, load_time: float = 0.0, file_size: int = 0, last_modified: float = 0.0, cache_hit_rate: float = 0.0, access_count: int = 0)[source]

Bases: object

Statistics for symbol library performance tracking.

access_count: int = 0
cache_hit_rate: float = 0.0
file_size: int = 0
last_modified: float = 0.0
library_path: Path
load_time: float = 0.0
symbol_count: int = 0
class kicad_sch_api.library.cache.SymbolDefinition(lib_id: str, name: str, library: str, reference_prefix: str, description: str = '', keywords: str = '', datasheet: str = '', pins: ~typing.List[~kicad_sch_api.core.types.SchematicPin] = <factory>, units: int = 1, unit_names: ~typing.Dict[int, str] = <factory>, power_symbol: bool = False, graphic_elements: ~typing.List[~typing.Dict[str, ~typing.Any]] = <factory>, property_positions: ~typing.Dict[str, ~typing.Tuple[float, float, float]] = <factory>, raw_kicad_data: ~typing.Any = None, extends: str | None = None, load_time: float = 0.0, access_count: int = 0, last_accessed: float = <factory>)[source]

Bases: object

Complete definition of a symbol from KiCAD library.

__post_init__()[source]

Post-initialization processing.

access_count: int = 0
property bounding_box: Tuple[float, float, float, float]

Calculate symbol bounding box from graphic elements and pins.

Returns:

(min_x, min_y, max_x, max_y) in mm

datasheet: str = ''
description: str = ''
extends: str | None = None
get_pin(pin_number: str) SchematicPin | None[source]

Get pin by number.

get_pins_by_type(pin_type: PinType) List[SchematicPin][source]

Get all pins of specified type.

graphic_elements: List[Dict[str, Any]]
keywords: str = ''
last_accessed: float
lib_id: str
library: str
list_pins() List[Dict[str, Any]][source]

List all pins for this symbol.

Returns:

  • number: Pin number (str)

  • name: Pin name (str)

  • type: Pin electrical type (str)

  • position: Pin position in symbol space (Point)

Return type:

List of pin dictionaries with keys

Example

>>> symbol = get_symbol_info("Device:R")
>>> pins = symbol.list_pins()
>>> print(f"Symbol has {len(pins)} pins")
>>> for pin in pins:
...     print(f"Pin {pin['number']}: {pin['name']}")
load_time: float = 0.0
name: str
pins: List[SchematicPin]
power_symbol: bool = False
property_positions: Dict[str, Tuple[float, float, float]]
raw_kicad_data: Any = None
reference_prefix: str
show_pins() None[source]

Display pin information in readable table format.

Prints a formatted table showing pin number, name, and electrical type for all pins in the symbol.

Example

>>> symbol = get_symbol_info("Device:R")
>>> symbol.show_pins()
Pins for Device:R:
Pin#   Name                 Type
----------------------------------------
1      ~                    PASSIVE
2      ~                    PASSIVE
property size: Tuple[float, float]

Get symbol size (width, height) in mm.

unit_names: Dict[int, str]
units: int = 1
class kicad_sch_api.library.cache.SymbolLibraryCache(cache_dir: Path | None = None, enable_persistence: bool = True)[source]

Bases: object

High-performance cache for KiCAD symbol libraries.

Features: - Intelligent caching with performance metrics - Fast symbol lookup and indexing - Library discovery and management - Memory-efficient storage - Cache invalidation based on file modification time

__init__(cache_dir: Path | None = None, enable_persistence: bool = True)[source]

Initialize the symbol cache.

Parameters:
  • cache_dir – Directory to store cached symbol data

  • enable_persistence – Whether to persist cache to disk

add_library_path(library_path: str | Path) bool[source]

Add a library path to the cache.

Parameters:

library_path – Path to .kicad_sym file

Returns:

True if library was added successfully

clear_cache()[source]

Clear all cached symbol data.

discover_libraries(search_paths: List[str | Path] = None) int[source]

Automatically discover KiCAD symbol libraries.

Searches environment variables and system paths for KiCAD symbol libraries. Supports version-flexible discovery across KiCAD 7, 8, 9, and custom installations.

Environment variables checked: - KICAD_SYMBOL_DIR (generic, supports : or ; separated paths) - KICAD9_SYMBOL_DIR (KiCAD 9 specific) - KICAD8_SYMBOL_DIR (KiCAD 8 specific) - KICAD7_SYMBOL_DIR (KiCAD 7 specific)

Parameters:

search_paths – Optional custom directories to search for .kicad_sym files. If None, uses environment variables + default system paths.

Returns:

Number of libraries discovered and added

get_library_symbols(library_name: str) List[SymbolDefinition][source]

Get all symbols from a specific library.

get_performance_stats() Dict[str, Any][source]

Get cache performance statistics.

get_symbol(lib_id: str) SymbolDefinition | None[source]

Get symbol definition by lib_id.

Parameters:

lib_id – Symbol identifier (e.g., β€œDevice:R”)

Returns:

Symbol definition if found, None otherwise

get_symbol_info(lib_id: str)[source]

Get symbol metadata for library introspection.

Returns SymbolInfo with unit count, names, and other metadata. Used by LLMs to query multi-unit component information before adding.

Parameters:

lib_id – Library identifier (e.g., β€œAmplifier_Operational:TL072”)

Returns:

SymbolInfo object with symbol metadata

Raises:

LibraryError – If symbol not found

Example

info = cache.get_symbol_info(β€œAmplifier_Operational:TL072”) print(f”Units: {info.unit_count}”) # 3 print(f”Unit names: {info.unit_names}”) # {1: β€œA”, 2: β€œB”, 3: β€œC”}

search_symbols(query: str, library: str | None = None, limit: int = 50) List[SymbolDefinition][source]

Search for symbols by name, description, or keywords.

Parameters:
  • query – Search query string

  • library – Optional library name to search within

  • limit – Maximum number of results

Returns:

List of matching symbol definitions

kicad_sch_api.library.cache.get_symbol_cache() SymbolLibraryCache[source]

Get the global symbol cache instance.

kicad_sch_api.library.cache.get_symbol_info(lib_id: str) SymbolDefinition | None[source]

Get symbol information from the library.

Convenience function that uses the global symbol cache to retrieve complete symbol information including pins, description, and metadata.

Parameters:

lib_id – Library identifier (e.g., β€œDevice:R”, β€œRF_Module:ESP32-WROOM-32”)

Returns:

SymbolDefinition with complete symbol information, or None if not found

Example

>>> import kicad_sch_api as ksa
>>> symbol = ksa.get_symbol_info('RF_Module:ESP32-WROOM-32')
>>> if symbol:
...     symbol.show_pins()  # Display pin table
Pins for RF_Module:ESP32-WROOM-32:
Description: WiFi/Bluetooth module
Pin#   Name                 Type
----------------------------------------
1      GND                  POWER_IN
2      3V3                  POWER_IN
...
>>> pins = symbol.list_pins()  # Get pin data
>>> print(f"Symbol has {len(pins)} pins")
kicad_sch_api.library.cache.search_symbols(query: str, library: str | None = None, limit: int = 50) List[SymbolDefinition][source]

Search for symbols by name, description, or keywords.

Convenience function that uses the global symbol cache to search for symbols matching the query string.

Parameters:
  • query – Search query string (searches in name, description, keywords)

  • library – Optional library name to search within (e.g., β€œDevice”, β€œRF_Module”)

  • limit – Maximum number of results to return (default: 50)

Returns:

List of SymbolDefinition objects matching the query

Example

>>> import kicad_sch_api as ksa
>>> # Search for all resistors
>>> resistors = ksa.search_symbols('resistor')
>>> for symbol in resistors:
...     print(f"{symbol.lib_id}: {symbol.description}")
>>> # Search only in Device library
>>> devices = ksa.search_symbols('capacitor', library='Device')
>>> # Search for ESP32 modules
>>> esp_modules = ksa.search_symbols('ESP32', library='RF_Module')
>>> for module in esp_modules:
...     module.show_pins()
kicad_sch_api.library.cache.set_symbol_cache(cache: SymbolLibraryCache)[source]

Set the global symbol cache instance.

Symbol Resolver

Symbol resolution with inheritance support for KiCAD symbols.

Provides authoritative symbol inheritance and resolution, separating this concern from caching for better testability and maintainability.

class kicad_sch_api.symbols.resolver.SymbolResolver(cache: ISymbolCache)[source]

Bases: object

Authoritative symbol inheritance and resolution.

Handles the complex logic of resolving symbol inheritance chains while maintaining clean separation from caching concerns.

__init__(cache: ISymbolCache)[source]

Initialize symbol resolver.

Parameters:

cache – Symbol cache implementation

clear_inheritance_cache() None[source]

Clear the inheritance resolution cache.

get_inheritance_chain(lib_id: str) List[str][source]

Get the complete inheritance chain for a symbol.

Parameters:

lib_id – Symbol to get chain for

Returns:

List of lib_ids in inheritance order (child to parent)

get_inheritance_statistics() Dict[str, Any][source]

Get inheritance resolution statistics.

Returns:

Dictionary with inheritance statistics

resolve_symbol(lib_id: str) SymbolDefinition | None[source]

Resolve symbol with full inheritance chain.

Parameters:

lib_id – Library identifier (e.g., β€œDevice:R”)

Returns:

Fully resolved symbol with inheritance applied, or None if not found

validate_inheritance_chain(lib_id: str) List[str][source]

Validate inheritance chain for cycles and missing parents.

Parameters:

lib_id – Symbol to validate

Returns:

List of issues found (empty if valid)

Symbol Validators

Symbol validation for KiCAD symbol definitions.

Provides comprehensive validation for symbol definitions, inheritance chains, and symbol data integrity.

class kicad_sch_api.symbols.validators.SymbolValidator(cache: ISymbolCache | None = None)[source]

Bases: object

Comprehensive validator for symbol definitions and inheritance.

Provides detailed validation with specific error reporting for symbol issues that could affect schematic generation.

__init__(cache: ISymbolCache | None = None)[source]

Initialize symbol validator.

Parameters:

cache – Optional symbol cache for inheritance validation

get_validation_summary(issues: List[ValidationIssue]) Dict[str, Any][source]

Get validation summary statistics.

Parameters:

issues – List of validation issues

Returns:

Summary dictionary with issue counts and severity

validate_inheritance_chain(symbol: SymbolDefinition) List[ValidationIssue][source]

Validate symbol inheritance chain for cycles and missing parents.

Parameters:

symbol – Symbol to validate inheritance for

Returns:

List of inheritance-related validation issues

validate_lib_id(lib_id: str) bool[source]

Validate library ID format.

Parameters:

lib_id – Library identifier to validate

Returns:

True if lib_id format is valid

validate_symbol(symbol: SymbolDefinition) List[ValidationIssue][source]

Validate a symbol definition comprehensively.

Parameters:

symbol – Symbol to validate

Returns:

List of validation issues found

validate_symbol_integrity(symbol: SymbolDefinition) List[ValidationIssue][source]

Validate symbol data integrity and consistency.

Parameters:

symbol – Symbol to validate

Returns:

List of integrity validation issues

Discovery

SQLite-based search index for fast component discovery.

This module creates and maintains a lightweight SQLite database for fast multi-field component searches, built from the existing SymbolDefinition cache.

class kicad_sch_api.discovery.search_index.ComponentSearchIndex(cache_dir: Path | None = None)[source]

Bases: object

Fast SQLite-based search index for KiCAD components.

__init__(cache_dir: Path | None = None)[source]

Initialize the search index.

get_categories() List[Dict[str, Any]][source]

Get all component categories with counts.

get_libraries() List[Dict[str, Any]][source]

Get all available libraries with component counts.

get_stats() Dict[str, Any][source]

Get search index statistics.

rebuild_index(progress_callback: callable | None = None) int[source]

Rebuild the search index from the symbol cache.

search(query: str, library: str | None = None, category: str | None = None, limit: int = 20) List[Dict[str, Any]][source]

Search components using multiple strategies.

validate_component(lib_id: str) Dict[str, Any] | None[source]

Check if a component exists in the index.

kicad_sch_api.discovery.search_index.ensure_index_built(rebuild: bool = False) int[source]

Ensure the search index is built and up-to-date.

kicad_sch_api.discovery.search_index.get_search_index() ComponentSearchIndex[source]

Get the global search index instance.

Utilities

Validation

Validation utilities for KiCAD schematic manipulation.

This module provides comprehensive validation capabilities including error collection, syntax validation, and semantic checking for schematic operations.

class kicad_sch_api.utils.validation.SchematicValidator(strict: bool = False)[source]

Bases: object

Comprehensive validator for schematic data structures and operations.

Provides validation for: - S-expression syntax - Component references and properties - Library references - Basic electrical connectivity

__init__(strict: bool = False)[source]

Initialize validator.

Parameters:

strict – If True, warnings are treated as errors

get_summary() Dict[str, int][source]

Get summary of validation issues by level.

has_errors() bool[source]

Check if any error-level issues were found.

has_warnings() bool[source]

Check if any warning-level issues were found.

validate_component(component_data: Dict[str, Any]) List[ValidationIssue][source]

Validate a single component.

validate_lib_id(lib_id: str) bool[source]

Validate library ID format.

Parameters:

lib_id – Library ID to validate (e.g., β€œDevice:R”)

Returns:

True if lib_id is valid

validate_reference(reference: str) bool[source]

Validate component reference format.

Parameters:

reference – Reference to validate (e.g., β€œR1”, β€œU5”, β€œ#PWR01”)

Returns:

True if reference is valid

validate_schematic_data(schematic_data: Dict[str, Any]) List[ValidationIssue][source]

Validate complete schematic data structure.

Parameters:

schematic_data – Parsed schematic data

Returns:

List of validation issues found

exception kicad_sch_api.utils.validation.ValidationError(message: str, issues: List[ValidationIssue] | None = None, field: str = '', value: Any = None)[source]

Bases: KiCadSchError

Raised when validation fails.

Supports rich error context with field/value information and can collect multiple validation issues.

__init__(message: str, issues: List[ValidationIssue] | None = None, field: str = '', value: Any = None)[source]

Initialize validation error with context.

Parameters:
  • message – Error message describing the validation failure

  • issues – List of validation issues (for collecting multiple errors)

  • field – The field name that failed validation

  • value – The invalid value that was provided

add_issue(issue: ValidationIssue) None[source]

Add a validation issue to this error.

get_errors() List[ValidationIssue][source]

Get only error-level issues.

get_warnings() List[ValidationIssue][source]

Get only warning-level issues.

class kicad_sch_api.utils.validation.ValidationIssue(category: str, message: str, level: ValidationLevel, context: Dict[str, Any] | None = None, suggestion: str | None = None)[source]

Bases: object

Single validation issue with context.

category: str
context: Dict[str, Any] | None = None
level: ValidationLevel
message: str
suggestion: str | None = None
class kicad_sch_api.utils.validation.ValidationLevel(*values)[source]

Bases: Enum

Validation issue severity levels.

CRITICAL = 'critical'
ERROR = 'error'
INFO = 'info'
WARNING = 'warning'
kicad_sch_api.utils.validation.collect_validation_errors(func)[source]

Decorator to collect validation errors from operations.

Usage:

@collect_validation_errors def my_operation():

# … operation that might have validation issues

kicad_sch_api.utils.validation.validate_schematic_file(file_path: str) List[ValidationIssue][source]

Convenience function to validate a schematic file.

Parameters:

file_path – Path to .kicad_sch file

Returns:

List of validation issues

Geometry

Geometry utilities for KiCAD schematic manipulation.

Provides coordinate transformation, pin positioning, and geometric calculations migrated from circuit-synth for improved maintainability.

kicad_sch_api.core.geometry.apply_transformation(point: Tuple[float, float], origin: Point, rotation: float, mirror: str | None = None) Tuple[float, float][source]

Apply rotation and mirroring transformation to a point.

Migrated from circuit-synth for accurate pin position calculation.

CRITICAL: Symbol coordinates use normal Y-axis (+Y is up), but schematic coordinates use inverted Y-axis (+Y is down). We must negate Y from symbol space before applying transformations.

Parameters:
  • point – Point to transform (x, y) relative to origin in SYMBOL space

  • origin – Component origin point in SCHEMATIC space

  • rotation – Rotation in degrees (0, 90, 180, 270)

  • mirror – Mirror axis (β€œx” or β€œy” or None)

Returns:

Transformed absolute position (x, y) in SCHEMATIC space

kicad_sch_api.core.geometry.calculate_position_for_pin(pin_local_position: Point | Tuple[float, float], desired_pin_position: Point | Tuple[float, float], rotation: float = 0.0, mirror: str | None = None, grid_size: float = 1.27) Point[source]

Calculate component position needed to place a specific pin at a desired location.

This is the inverse of get_pin_position() - given where you want a pin to be, it calculates where the component center needs to be placed.

Useful for aligning components by their pins rather than their centers, which is essential for clean horizontal signal flows without unnecessary wire jogs.

Parameters:
  • pin_local_position – Pin position in symbol space (from symbol definition)

  • desired_pin_position – Where you want the pin to be in schematic space

  • rotation – Component rotation in degrees (0, 90, 180, 270)

  • mirror – Mirror axis (β€œx” or β€œy” or None) - currently unused

  • grid_size – Grid size for snapping result (default 1.27mm = 50mil)

Returns:

Component position that will place the pin at desired_pin_position

Example

>>> # Place resistor so pin 2 is at (150, 100)
>>> pin_pos = Point(0, -3.81)  # Pin 2 local position from symbol
>>> comp_pos = calculate_position_for_pin(pin_pos, (150, 100))
>>> # Now add component at comp_pos, and pin 2 will be at (150, 100)

Note

The result is automatically snapped to the KiCAD grid for proper connectivity. This function matches the behavior of SchematicSymbol.get_pin_position().

kicad_sch_api.core.geometry.distance_between_points(p1: Tuple[float, float], p2: Tuple[float, float]) float[source]

Calculate distance between two points.

Parameters:
  • p1 – First point (x, y)

  • p2 – Second point (x, y)

Returns:

Distance between points

kicad_sch_api.core.geometry.points_equal(p1: Point, p2: Point, tolerance: float = 0.01) bool[source]

Check if two points are equal within tolerance.

Parameters:
  • p1 – First point

  • p2 – Second point

  • tolerance – Distance tolerance

Returns:

True if points are equal within tolerance

kicad_sch_api.core.geometry.snap_to_grid(position: Tuple[float, float], grid_size: float = 2.54) Tuple[float, float][source]

Snap a position to the nearest grid point.

Parameters:
  • position – (x, y) coordinate

  • grid_size – Grid size in mm (default 2.54mm = 0.1 inch)

Returns:

Grid-aligned (x, y) coordinate

Font metrics and text rendering constants for KiCad schematic text.

These constants are used for accurate text bounding box calculations and symbol spacing in schematic layouts.

symbol_bbox.py

Calculate accurate bounding boxes for KiCad symbols based on their graphical elements. This ensures proper spacing and collision detection in schematic layouts.

Migrated from circuit-synth to kicad-sch-api for better architectural separation.

class kicad_sch_api.geometry.symbol_bbox.SymbolBoundingBoxCalculator[source]

Bases: object

Calculate the actual bounding box of a symbol from its graphical elements.

DEFAULT_PIN_LENGTH = 2.54
DEFAULT_PIN_NAME_OFFSET = 0.508
DEFAULT_PIN_NUMBER_SIZE = 1.27
DEFAULT_PIN_TEXT_WIDTH_RATIO = 0.65
DEFAULT_TEXT_HEIGHT = 2.54
classmethod calculate_bounding_box(symbol_data: Dict[str, Any], include_properties: bool = True, hierarchical_labels: List[Dict[str, Any]] | None = None, pin_net_map: Dict[str, str] | None = None) Tuple[float, float, float, float][source]

Calculate the actual bounding box of a symbol from its graphical elements.

Parameters:
  • symbol_data – Dictionary containing symbol definition from KiCad library

  • include_properties – Whether to include space for Reference/Value labels

  • hierarchical_labels – List of hierarchical labels attached to this symbol

  • pin_net_map – Optional mapping of pin numbers to net names (for accurate label sizing)

Returns:

Tuple of (min_x, min_y, max_x, max_y) in mm

Raises:

ValueError – If symbol data is invalid or bounding box cannot be calculated

classmethod calculate_placement_bounding_box(symbol_data: Dict[str, Any]) Tuple[float, float, float, float][source]

Calculate bounding box for PLACEMENT purposes - excludes pin labels.

This method calculates a tighter bounding box that only includes: - Component body (shapes/graphics) - Pin endpoints (without label text) - Small margin for component properties

Pin label text is excluded because it extends arbitrarily far based on text length and would cause incorrect spacing in text-flow placement.

Parameters:

symbol_data – Dictionary containing symbol definition from KiCad library

Returns:

Tuple of (min_x, min_y, max_x, max_y) in mm

Raises:

ValueError – If symbol data is invalid or bounding box cannot be calculated

classmethod calculate_visual_bounding_box(symbol_data: Dict[str, Any], pin_net_map: Dict[str, str] | None = None) Tuple[float, float, float, float][source]

Calculate bounding box for visual/debug drawing (includes pin labels, no property spacing).

This shows the actual component geometry including pin labels. Use this for drawing bounding boxes on schematics.

Parameters:
  • symbol_data – Dictionary containing symbol definition

  • pin_net_map – Optional mapping of pin numbers to net names (for accurate label sizing)

Returns:

Tuple of (min_x, min_y, max_x, max_y) in mm

classmethod get_symbol_dimensions(symbol_data: Dict[str, Any], include_properties: bool = True, pin_net_map: Dict[str, str] | None = None) Tuple[float, float][source]

Get the width and height of a symbol.

Parameters:
  • symbol_data – Dictionary containing symbol definition

  • include_properties – Whether to include space for Reference/Value labels

  • pin_net_map – Optional mapping of pin numbers to net names

Returns:

Tuple of (width, height) in mm