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:
objectEnhanced 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
- get_pin(pin_number: str) SchematicPin | None[source]ο
Get pin by number.
- 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.
- 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)
- property pins: List[SchematicPin]ο
List of component pins.
- 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 β¦
- validate() List[ValidationIssue][source]ο
Validate this component.
- 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.
- __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:
KeyError β If UUID or reference not found
IndexError β If index out of range
TypeError β If key is invalid type
- __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).
- 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)
- validate_all() List[ValidationIssue][source]ο
Validate all components in collection.
- exception kicad_sch_api.DuplicateElementError(message: str, element_type: str = '', identifier: str = '')[source]ο
Bases:
CollectionErrorRaised 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:
CollectionErrorRaised 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:
objectCentral 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
- exception kicad_sch_api.KiCadSchError[source]ο
Bases:
ExceptionBase 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:
objectComplete 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).
- class kicad_sch_api.Schematic(schematic_data: Dict[str, Any] = None, file_path: str | None = None, name: str | None = None)[source]ο
Bases:
objectProfessional 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.
- __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
- 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')
- 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_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:
FileNotFoundError β If file doesnβt exist
ValidationError β If file is invalid or corrupted
- 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.
- validate() List[ValidationIssue][source]ο
Perform comprehensive schematic validation.
- Returns:
List of validation issues found
- 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:
objectHigh-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
- 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_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:
KiCadSchErrorRaised 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:
objectSingle validation issue with context.
- level: ValidationLevelο
- 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:
objectProfessional 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.
- __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
- 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')
- 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_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:
FileNotFoundError β If file doesnβt exist
ValidationError β If file is invalid or corrupted
- 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.
- validate() List[ValidationIssue][source]ο
Perform comprehensive schematic validation.
- Returns:
List of validation issues found
- property wires: WireCollectionο
Collection of all wires in the schematic.
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]ο
-
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
- __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
- 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
- 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
- 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:
objectContext manager for batch operations.
- __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:
objectCentralized 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
- class kicad_sch_api.collections.base.IndexSpec(name: str, key_func: Callable[[Any], Any], unique: bool = True, description: str = '')[source]ο
Bases:
objectSpecification for a collection index.
Defines how to build and maintain an index for fast lookups.
- class kicad_sch_api.collections.base.PropertyDict(data: Dict[str, Any] | None = None, on_modify: Callable[[], None] | None = None)[source]ο
Bases:
MutableMappingDictionary that automatically tracks modifications.
Wraps a dictionary and notifies a callback when any changes occur. Implements the full MutableMapping interface.
- class kicad_sch_api.collections.base.ValidationLevel(*values)[source]ο
Bases:
EnumValidation 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ο
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:
objectEnhanced 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
- 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 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
Set of property names that have (hide yes) flag.
- 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 pins: List[SchematicPin]ο
List of component pins.
- 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)
- 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 β¦
- 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
- validate() List[ValidationIssue][source]ο
Validate this component.
- Returns:
List of validation issues (empty if valid)
- 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:
KeyError β If UUID or reference not found
IndexError β If index out of range
TypeError β If key is invalid type
- __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
- 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
- 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
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
- 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:
objectEnhanced 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
- to_dict() Dict[str, Any][source]ο
Convert label to dictionary representation.
- Returns:
Dictionary with label data
- 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
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:
objectEnhanced 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
- get_pin(pin_number: str) SchematicPin | None[source]ο
Get pin by number.
- 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.
- 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)
- property pins: List[SchematicPin]ο
List of component pins.
- 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 β¦
- validate() List[ValidationIssue][source]ο
Validate this component.
- 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.
- __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:
KeyError β If UUID or reference not found
IndexError β If index out of range
TypeError β If key is invalid type
- __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).
- 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)
- 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
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.
- __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
- 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.
- class kicad_sch_api.core.labels.LabelElement(label_data: Label, parent_collection: LabelCollection)[source]ο
Bases:
objectEnhanced 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
- 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
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.
- __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
- 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
- class kicad_sch_api.core.texts.TextElement(text_data: Text, parent_collection: TextCollection)[source]ο
Bases:
objectEnhanced 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
- 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:
objectBus entry point connecting individual wires to buses.
- class kicad_sch_api.core.types.HierarchicalLabelShape(*values)[source]ο
Bases:
EnumHierarchical 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:
objectImage element in schematic.
- 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:
objectJunction point where multiple wires meet.
- 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:
objectText label in schematic.
- shape: HierarchicalLabelShape | None = Noneο
- class kicad_sch_api.core.types.LabelType(*values)[source]ο
Bases:
EnumLabel 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:
objectElectrical net connecting components.
- class kicad_sch_api.core.types.NoConnect(uuid: str, position: Point)[source]ο
Bases:
objectNo-connect symbol in schematic.
- 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:
objectComplete 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).
- class kicad_sch_api.core.types.PinShape(*values)[source]ο
Bases:
EnumKiCAD 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:
EnumKiCAD 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:
object2D point with x,y coordinates in mm.
- class kicad_sch_api.core.types.Rectangle(top_left: Point, bottom_right: Point)[source]ο
Bases:
objectRectangle defined by two corner points.
- 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:
objectComplete schematic data structure.
- components: List[SchematicSymbol]ο
- get_component(reference: str) SchematicSymbol | None[source]ο
Get component by reference.
- rectangles: List[SchematicRectangle]ο
- title_block: TitleBlockο
- 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:
objectPin definition for schematic symbols.
- 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:
objectGraphical rectangle element in schematic.
- 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:
objectComponent 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)
- 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
- instances: List[SymbolInstance]ο
- pins: List[SchematicPin]ο
- 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})
- 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:
objectHierarchical sheet in schematic.
- class kicad_sch_api.core.types.SheetPin(uuid: str, name: str, position: Point, pin_type: PinType = PinType.BIDIRECTIONAL, size: float = 1.27)[source]ο
Bases:
objectPin on hierarchical sheet.
- 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:
objectSymbol 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.
- pins: List[SchematicPin]ο
- class kicad_sch_api.core.types.SymbolInstance(path: str, reference: str, unit: int = 1, project: str = '')[source]ο
Bases:
objectInstance of a symbol from library.
- 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:
objectFree text element in schematic.
- 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:
objectText box element with border in schematic.
- 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:
objectTitle block information.
- 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:
objectWire connection in schematic.
- class kicad_sch_api.core.types.WireType(*values)[source]ο
Bases:
EnumWire 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:
objectDefault values for various operations.
- 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:
objectCommon S-expression field names to avoid typos.
- 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:
objectKiCAD file format identifiers and version strings.
- 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:
objectStandard KiCAD grid and spacing settings.
- class kicad_sch_api.core.config.KiCADConfig[source]ο
Bases:
objectCentral 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
- class kicad_sch_api.core.config.PaperSizeConstants(default: str = 'A4', valid_sizes: ~typing.List[str] = <factory>)[source]ο
Bases:
objectStandard paper size definitions.
- class kicad_sch_api.core.config.PositioningSettings(use_grid_units: bool = False, grid_size: float = 1.27)[source]ο
Bases:
objectGlobal positioning behavior settings.
- 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:
objectStandard property positioning offsets relative to component position.
- 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:
objectHierarchical sheet positioning settings.
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:
objectHigh-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:
FileNotFoundError β If file doesnβt exist
ValidationError β If parsing fails or validation issues found
- 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.
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:
ExactFormatterCompact formatter for minimal output size.
- class kicad_sch_api.core.formatter.DebugFormatter[source]ο
Bases:
ExactFormatterDebug formatter with extra spacing and comments.
- class kicad_sch_api.core.formatter.ExactFormatter[source]ο
Bases:
objectS-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.
- 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
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:
BaseElementParserParser for Component symbol elements.
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:
BaseElementParserParser for wire and connection elements.
Label and hierarchical label elements parser for KiCAD schematics.
Handles parsing and serialization of Label and hierarchical label elements.
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:
objectStatistics for symbol library performance tracking.
- 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:
objectComplete definition of a symbol from KiCAD library.
- 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
- 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.
- 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']}")
- pins: List[SchematicPin]ο
- 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
- class kicad_sch_api.library.cache.SymbolLibraryCache(cache_dir: Path | None = None, enable_persistence: bool = True)[source]ο
Bases:
objectHigh-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
- 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_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:
objectAuthoritative 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
- 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
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:
objectComprehensive 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:
objectFast SQLite-based search index for KiCAD components.
- rebuild_index(progress_callback: callable | None = None) int[source]ο
Rebuild the search index from the symbol cache.
- 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:
objectComprehensive 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
- 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
- exception kicad_sch_api.utils.validation.ValidationError(message: str, issues: List[ValidationIssue] | None = None, field: str = '', value: Any = None)[source]ο
Bases:
KiCadSchErrorRaised 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:
objectSingle validation issue with context.
- level: ValidationLevelο
- class kicad_sch_api.utils.validation.ValidationLevel(*values)[source]ο
Bases:
EnumValidation 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:
objectCalculate 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