Detailed Module Documentation

This section contains the complete auto-generated API documentation for all modules.

Base Classes

kicadfiles.base_element module

Optimized S-expression parser for KiCad objects with cursor-based approach.

class ABC[source]

Bases: object

Helper class that provides a standard way to create an ABC using inheritance.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class Enum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: object

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

    >>> Color.RED
    <Color.RED: 1>
    
  • value lookup:

    >>> Color(1)
    <Color.RED: 1>
    
  • name lookup:

    >>> Color['RED']
    <Color.RED: 1>
    

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

class FieldInfo(name, field_type, inner_type, position_index, token_name=None)[source]

Bases: object

Complete field information for optimized parsing.

__init__(name, field_type, inner_type, position_index, token_name=None)
class FieldType(*values)[source]

Bases: Enum

Optimized classification with correct Optional/Required handling.

KICAD_OBJECT = 'kicad_object'
KICAD_PRIMITIVE = 'kicad_primitive'
LIST = 'list'
OPTIONAL_FLAG = 'optional_flag'
OPTIONAL_KICAD_OBJECT = 'optional_kicad_object'
OPTIONAL_KICAD_PRIMITIVE = 'optional_kicad_primitive'
OPTIONAL_PRIMITIVE = 'optional_primitive'
PRIMITIVE = 'primitive'
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadPrimitive(token_name, value=None, required=True)[source]

Bases: ABC

Base class for KiCad primitive values - simplified like OptionalFlag.

__bool__()[source]

Boolean conversion - returns True if found and has truthy value.

__call__(value)[source]

Set value using function call syntax: primitive(new_value).

__eq__(other)[source]

Equality comparison excluding __found__ field.

__init__(token_name, value=None, required=True)
__repr__()[source]

Developer-friendly representation.

to_sexpr()[source]

Convert to S-expression format.

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class ParseCursor(sexpr, parser, path, strictness)[source]

Bases: object

Lightweight cursor for tracking position in S-expression.

__init__(sexpr, parser, path, strictness)
enter(sexpr, name)[source]

Create new cursor for nested object.

get_path_str()[source]
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class SExprParser(sexpr)[source]

Bases: object

Minimal S-Expression parser with usage tracking always enabled.

__init__(sexpr)[source]

Initialize parser with an S-expression.

Parameters:

sexpr (List[Any]) – Parsed S-expression as nested lists/atoms

classmethod from_string(sexpr_string)[source]

Create parser from S-expression string.

Parameters:

sexpr_string (str) – String containing S-expression data

Returns:

New parser instance

Return type:

SExprParser

get_unused_parameters()[source]

Get list of unused parameters.

Returns:

List of unused parameters (excluding token name at index 0)

Return type:

List[Any]

mark_used(index)[source]

Mark a parameter index as used.

Parameters:

index (int) – Index in sexpr that was accessed

class Symbol(object, position=None)[source]

Bases: String

class TypeVar

Bases: object

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

cast(typ, val)[source]

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

fields(class_or_instance)[source]

Return a tuple describing the fields of this dataclass.

Accepts a dataclass or an instance of one. Tuple elements are of type Field.

get_args(tp)[source]

Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed.

Examples:

>>> T = TypeVar('T')
>>> assert get_args(Dict[str, int]) == (str, int)
>>> assert get_args(int) == ()
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
>>> assert get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)[source]

Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types.

Examples:

>>> P = ParamSpec('P')
>>> assert get_origin(Literal[42]) is Literal
>>> assert get_origin(int) is None
>>> assert get_origin(ClassVar[int]) is ClassVar
>>> assert get_origin(Generic) is Generic
>>> assert get_origin(Generic[T]) is Generic
>>> assert get_origin(Union[T, int]) is Union
>>> assert get_origin(List[Tuple[T, T]][int]) is list
>>> assert get_origin(P.args) is P
get_type_hints(obj, globalns=None, localns=None, include_extras=False)[source]

Return type hints for an object.

This is often the same as obj.__annotations__, but it handles forward references encoded as string literals and recursively replaces all ‘Annotated[T, …]’ with ‘T’ (unless ‘include_extras=True’).

The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members.

TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present.

BEWARE – the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals.

  • If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module’s globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. For classes, the search order is globals first then locals.

  • If one dict argument is passed, it is used for both globals and locals.

  • If two dict arguments are passed, they specify globals and locals, respectively.

str_to_sexpr(content)[source]

Convert string content to S-expression.

Parameters:

content (str) – String content containing S-expression data

Returns:

Parsed S-expression as nested lists/atoms

Raises:

ValueError – If content cannot be parsed as valid S-expression

Return type:

List[Any]

kicadfiles.base_types module

Base types for KiCad S-expressions - fundamental elements with no cross-dependencies.

class Anchor(pad_shape=PadShape.RECT)[source]

Bases: KiCadObject

Anchor pad shape definition for custom pads.

The ‘anchor’ token defines the anchor pad shape of a custom pad in the format:

(anchor PAD_SHAPE)
Parameters:

pad_shape (PadShape) – Anchor pad shape (rect or circle)

__init__(pad_shape=PadShape.RECT)
class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class AtXY(x=0.0, y=0.0)[source]

Bases: KiCadObject

Position identifier token for elements that only use X and Y coordinates.

The ‘at’ token defines positional coordinates in the format:

(at X Y)

Used for elements like junctions that don’t have rotation.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

__init__(x=0.0, y=0.0)
class Center(x=0.0, y=0.0)[source]

Bases: KiCadObject

Center point definition token.

The ‘center’ token defines a center point in the format:

(center X Y)
Parameters:
  • x (float) – Horizontal position of the center point

  • y (float) – Vertical position of the center point

__init__(x=0.0, y=0.0)
class Color(r=0, g=0, b=0, a=0)[source]

Bases: KiCadObject

Color definition token.

The ‘color’ token defines color values in the format:

(color R G B A)
Parameters:
  • r (int) – Red color component (0-255)

  • g (int) – Green color component (0-255)

  • b (int) – Blue color component (0-255)

  • a (int) – Alpha component (0-255)

__init__(r=0, g=0, b=0, a=0)
class Effects(font=None, justify=None, hide=<factory>, href=<factory>)[source]

Bases: KiCadObject

Text effects definition token.

The ‘effects’ token defines text formatting effects in the format:

(effects
    (font [size SIZE] [thickness THICKNESS] [bold] [italic])
    [(justify JUSTIFY)]
    [hide]
)
Parameters:
  • font (Font | None) – Font definition (optional)

  • justify (Justify | None) – Text justification (optional)

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • href (KiCadStr | None) – Hyperlink reference (optional)

__init__(font=None, justify=None, hide=<factory>, href=<factory>)
class End(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

End point definition token.

The ‘end’ token defines an end point in the format:

(end X Y)
Parameters:
  • x (float) – Horizontal position of the end point

  • y (float) – Vertical position of the end point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Fill(type=None, color=None)[source]

Bases: KiCadObject

Fill definition token.

The ‘fill’ token defines how schematic and symbol library graphical items are filled in the format: (fill

(type none | outline | background) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • type (Type | None) – Fill type specification (optional)

  • color (Color | None) – Fill color specification (optional)

__init__(type=None, color=None)
class Font(face=<factory>, size=None, thickness=<factory>, bold=<factory>, italic=<factory>, color=None)[source]

Bases: KiCadObject

Font definition token.

The ‘font’ token defines font properties in the format: (font [face “FONT_NAME”] [size WIDTH HEIGHT] [thickness THICKNESS] [bold] [italic])

Parameters:
  • face (KiCadStr | None) – Font face specification (optional)

  • size (Size | None) – Font size (optional)

  • thickness (KiCadFloat | None) – Font thickness (optional)

  • bold (OptionalFlag | None) – Bold flag (optional)

  • italic (OptionalFlag | None) – Italic flag (optional)

  • color (Color | None) – Font color (optional)

__init__(face=<factory>, size=None, thickness=<factory>, bold=<factory>, italic=<factory>, color=None)
class Justify(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)[source]

Bases: KiCadObject

Text justification definition token.

The ‘justify’ token defines text alignment and mirroring in the format:

(justify [left | right | center] [top | bottom | center] [mirror])
Parameters:
  • left (OptionalFlag | None) – Left horizontal justification flag (optional)

  • right (OptionalFlag | None) – Right horizontal justification flag (optional)

  • top (OptionalFlag | None) – Top vertical justification flag (optional)

  • bottom (OptionalFlag | None) – Bottom vertical justification flag (optional)

  • center (OptionalFlag | None) – Center justification flag (horizontal or vertical) (optional)

  • mirror (OptionalFlag | None) – Mirror text flag (optional)

__init__(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class Layer(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)[source]

Bases: KiCadObject

Layer definition token.

The ‘layer’ token defines layer information in the format:

(layer "NAME" | dielectric NUMBER (type "DESCRIPTION")
       [(color "COLOR")] [(thickness THICKNESS)]
       [(material "MATERIAL")] [(epsilon_r VALUE)]
       [(loss_tangent VALUE)])
For simple layer references:

(layer “LAYER_NAME”)

Parameters:
  • name (str) – Layer name or ‘dielectric’

  • number (int | None) – Layer stack number (optional)

  • type (str | None) – Layer type description (optional)

  • color (str | None) – Layer color as string (optional)

  • thickness (float | None) – Layer thickness value (optional)

  • material (str | None) – Material name (optional)

  • epsilon_r (float | None) – Dielectric constant value (optional)

  • loss_tangent (float | None) – Loss tangent value (optional)

__init__(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)
class Layers(layers=<factory>)[source]

Bases: KiCadObject

Layer list definition token.

The ‘layers’ token defines a list of layer names in the format:

(layers "F.Cu" "F.Paste" "F.Mask")
(layers "*.Cu" "*.Mask" "F.SilkS")

Used for pad layers, via layers, and other layer specifications.

layers

List of layer names

Type:

List[str]

Parameters:

layers (List[str]) – List of layer names

__init__(layers=<factory>)
class Mid(x=0.0, y=0.0)[source]

Bases: KiCadObject

Mid point definition token.

The ‘mid’ token defines a mid point in the format:

(mid X Y)
Parameters:
  • x (float) – Horizontal position of the mid point

  • y (float) – Vertical position of the mid point

__init__(x=0.0, y=0.0)
class Offset(x=0.0, y=0.0)[source]

Bases: KiCadObject

Offset definition token.

The ‘offset’ token defines an offset position in the format: (offset X Y)

Parameters:
  • x (float) – Horizontal offset coordinate

  • y (float) – Vertical offset coordinate

__init__(x=0.0, y=0.0)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class PadShape(*values)[source]

Bases: Enum

Pad shapes for footprints.

CIRCLE = 'circle'
CUSTOM = 'custom'
OVAL = 'oval'
RECT = 'rect'
ROUNDRECT = 'roundrect'
TRAPEZOID = 'trapezoid'
class Pos(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Position definition token.

The ‘pos’ token defines a position in the format: (pos X Y)

Parameters:
  • x (float) – Horizontal position coordinate

  • y (float) – Vertical position coordinate

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Property(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)[source]

Bases: KiCadObject

Property definition token.

The ‘property’ token defines properties in two formats:

General properties::

(property “KEY” “VALUE”)

Symbol properties::
(property

“KEY” “VALUE” (id N) POSITION_IDENTIFIER TEXT_EFFECTS

)

Parameters:
  • key (str) – Property key name (must be unique)

  • value (str) – Property value

  • id (KiCadStr | None) – Property ID (optional)

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • unlocked (OptionalFlag | None) – Whether property is unlocked (optional)

  • layer (Layer | None) – Layer assignment (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • hide (OptionalFlag | None) – Hide property flag (optional)

__init__(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)
class Pts(points=<factory>)[source]

Bases: KiCadObject

Coordinate point list definition token.

The ‘pts’ token defines a list of coordinate points in the format: (pts

(xy X Y) … (xy X Y)

)

Where each xy token defines a single X and Y coordinate pair. The number of points is determined by the object type.

Parameters:

points (List[Xy]) – List of 2D coordinate points

__init__(points=<factory>)
class Size(width=0.0, height=0.0)[source]

Bases: KiCadObject

Size definition token.

The ‘size’ token defines width and height dimensions in the format: (size WIDTH HEIGHT)

Parameters:
  • width (float) – Width dimension

  • height (float) – Height dimension

__init__(width=0.0, height=0.0)
class Start(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Start point definition token.

The ‘start’ token defines a start point in the format: (start X Y)

Parameters:
  • x (float) – Horizontal position of the start point

  • y (float) – Vertical position of the start point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Stroke(width=<factory>, type=<factory>, color=None)[source]

Bases: KiCadObject

Stroke definition token.

The ‘stroke’ token defines how the outlines of graphical objects are drawn in the format: (stroke

(width WIDTH) (type TYPE) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • width (KiCadFloat) – Line width specification

  • type (Type) – Stroke line style specification

  • color (Color | None) – Line color specification (optional)

__init__(width=<factory>, type=<factory>, color=None)
class StrokeType(*values)[source]

Bases: Enum

Valid stroke line styles for graphics.

DASH = 'dash'
DASH_DOT = 'dash_dot'
DASH_DOT_DOT = 'dash_dot_dot'
DEFAULT = 'default'
DOT = 'dot'
SOLID = 'solid'
class Text(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)[source]

Bases: KiCadObject

Text content definition token.

The ‘text’ token defines text content in the format: (text “TEXT_CONTENT”

(at X Y [ANGLE]) (effects EFFECTS)

)

Parameters:
  • content (str) – Text content

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether to exclude from simulation (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)
class Type(value='')[source]

Bases: KiCadObject

Type definition token.

The ‘type’ token defines a type value in the format: (type VALUE)

Parameters:

value (str) – Type value

__init__(value='')
to_sexpr()[source]

Custom serialization to ensure type values are never quoted.

class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class Xy(x=0.0, y=0.0)[source]

Bases: KiCadObject

2D coordinate definition token.

The ‘xy’ token defines a 2D coordinate point in the format: (xy X Y)

Parameters:
  • x (float) – Horizontal coordinate

  • y (float) – Vertical coordinate

__init__(x=0.0, y=0.0)
class Xyz(x=0.0, y=0.0, z=0.0)[source]

Bases: KiCadObject

3D coordinate definition token.

The ‘xyz’ token defines 3D coordinates in the format: (xyz X Y Z)

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

  • z (float) – Z coordinate

__init__(x=0.0, y=0.0, z=0.0)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.enums module

Common enumeration types for KiCad S-expressions.

class ClearanceType(*values)[source]

Bases: Enum

Custom pad clearance types.

CONVEXHULL = 'convexhull'
OUTLINE = 'outline'
class ConstraintType(*values)[source]

Bases: Enum

Design rule constraint types.

ANNULAR_WIDTH = 'annular_width'
ASSERTION = 'assertion'
BLIND_VIA_RATIO = 'blind_via_ratio'
CLEARANCE = 'clearance'
CONNECTION_WIDTH = 'connection_width'
COURTYARD_CLEARANCE = 'courtyard_clearance'
CREEPAGE = 'creepage'
DIFF_PAIR_GAP = 'diff_pair_gap'
DIFF_PAIR_UNCOUPLED = 'diff_pair_uncoupled'
DISALLOW = 'disallow'
EDGE_CLEARANCE = 'edge_clearance'
HOLE_CLEARANCE = 'hole_clearance'
HOLE_SIZE = 'hole_size'
HOLE_TO_HOLE = 'hole_to_hole'
LENGTH = 'length'
MICRO_VIA_DIAMETER = 'micro_via_diameter'
MICRO_VIA_DRILL = 'micro_via_drill'
MIN_RESOLVED_SPOKES = 'min_resolved_spokes'
PHYSICAL_CLEARANCE = 'physical_clearance'
PHYSICAL_HOLE_CLEARANCE = 'physical_hole_clearance'
SILK_CLEARANCE = 'silk_clearance'
SKEW = 'skew'
TEXT_HEIGHT = 'text_height'
TEXT_THICKNESS = 'text_thickness'
THERMAL_RELIEF_GAP = 'thermal_relief_gap'
THERMAL_SPOKE_WIDTH = 'thermal_spoke_width'
TRACK_WIDTH = 'track_width'
VIA_DIAMETER = 'via_diameter'
VIA_DRILL = 'via_drill'
ZONE_CONNECTION = 'zone_connection'
class Enum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: object

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

    >>> Color.RED
    <Color.RED: 1>
    
  • value lookup:

    >>> Color(1)
    <Color.RED: 1>
    
  • name lookup:

    >>> Color['RED']
    <Color.RED: 1>
    

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

class FillType(*values)[source]

Bases: Enum

Fill types for graphical objects.

BACKGROUND = 'background'
COLOR = 'color'
NONE = 'none'
OUTLINE = 'outline'
class FootprintTextType(*values)[source]

Bases: Enum

Footprint text types.

REFERENCE = 'reference'
USER = 'user'
VALUE = 'value'
class HatchStyle(*values)[source]

Bases: Enum

Zone hatch display styles.

EDGE = 'edge'
FULL = 'full'
NONE = 'none'
class JustifyHorizontal(*values)[source]

Bases: Enum

Horizontal text justification.

CENTER = 'center'
LEFT = 'left'
RIGHT = 'right'
class JustifyVertical(*values)[source]

Bases: Enum

Vertical text justification.

BOTTOM = 'bottom'
CENTER = 'center'
TOP = 'top'
class LabelShape(*values)[source]

Bases: Enum

Label and pin shapes for global labels, hierarchical labels, and sheet pins.

BIDIRECTIONAL = 'bidirectional'
INPUT = 'input'
OUTPUT = 'output'
PASSIVE = 'passive'
TRI_STATE = 'tri_state'
class LayerType(*values)[source]

Bases: Enum

PCB layer types.

JUMPER = 'jumper'
MIXED = 'mixed'
POWER = 'power'
SIGNAL = 'signal'
USER = 'user'
class PadShape(*values)[source]

Bases: Enum

Pad shapes for footprints.

CIRCLE = 'circle'
CUSTOM = 'custom'
OVAL = 'oval'
RECT = 'rect'
ROUNDRECT = 'roundrect'
TRAPEZOID = 'trapezoid'
class PadType(*values)[source]

Bases: Enum

Pad types for footprints.

CONNECT = 'connect'
NP_THRU_HOLE = 'np_thru_hole'
SMD = 'smd'
THRU_HOLE = 'thru_hole'
class PinElectricalType(*values)[source]

Bases: Enum

Pin electrical types for symbols.

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'
TRI_STATE = 'tri_state'
UNSPECIFIED = 'unspecified'
class PinGraphicStyle(*values)[source]

Bases: Enum

Pin graphical styles for symbols.

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 SeverityLevel(*values)[source]

Bases: Enum

Design rule severity levels.

ERROR = 'error'
EXCLUSION = 'exclusion'
IGNORE = 'ignore'
WARNING = 'warning'
class SmoothingStyle(*values)[source]

Bases: Enum

Zone corner smoothing styles.

CHAMFER = 'chamfer'
FILLET = 'fillet'
NONE = 'none'
class StrokeType(*values)[source]

Bases: Enum

Valid stroke line styles for graphics.

DASH = 'dash'
DASH_DOT = 'dash_dot'
DASH_DOT_DOT = 'dash_dot_dot'
DEFAULT = 'default'
DOT = 'dot'
SOLID = 'solid'
class ViaType(*values)[source]

Bases: Enum

Via types for PCB.

BLIND_BURIED = 'blind_buried'
MICRO = 'micro'
THROUGH = 'through'
class ZoneConnection(*values)[source]

Bases: Enum

Zone connection types for pads.

INHERITED = 0
NONE = 3
SOLID = 1
THERMAL_RELIEF = 2
class ZoneFillMode(*values)[source]

Bases: Enum

Zone fill modes.

HATCHED = 'hatched'
SOLID = 'solid'
class ZoneKeepoutSetting(*values)[source]

Bases: Enum

Zone keepout settings.

ALLOWED = 'allowed'
NOT_ALLOWED = 'not_allowed'

File Format Classes

kicadfiles.board_layout module

Board layout elements for KiCad S-expressions - PCB/board design and routing.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class End(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

End point definition token.

The ‘end’ token defines an end point in the format:

(end X Y)
Parameters:
  • x (float) – Horizontal position of the end point

  • y (float) – Vertical position of the end point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Footprint(library_link=None, version=<factory>, generator=<factory>, generator_version=<factory>, locked=<factory>, placed=<factory>, layer=<factory>, tedit=<factory>, uuid=None, at=None, descr=<factory>, tags=<factory>, properties=<factory>, path=None, attr=None, autoplace_cost90=None, autoplace_cost180=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_ratio=None, clearance=<factory>, zone_connect=None, thermal_width=<factory>, thermal_gap=<factory>, private_layers=<factory>, net_tie_pad_groups=None, pads=<factory>, models=<factory>, fp_elements=<factory>, embedded_fonts=<factory>, embedded_files=None)[source]

Bases: KiCadObject

Footprint definition token that defines a complete footprint.

The ‘footprint’ token defines a footprint with all its elements in the format:

(footprint
    ["LIBRARY_LINK"]
    [locked]
    [placed]
    (layer LAYER_DEFINITIONS)
    (tedit TIME_STAMP)
    [(uuid UUID)]
    [POSITION_IDENTIFIER]
    [(descr "DESCRIPTION")]
    [(tags "NAME")]
    [(property "KEY" "VALUE") ...]
    (path "PATH")
    [(autoplace_cost90 COST)]
    [(autoplace_cost180 COST)]
    [(solder_mask_margin MARGIN)]
    [(solder_paste_margin MARGIN)]
    [(solder_paste_ratio RATIO)]
    [(clearance CLEARANCE)]
    [(zone_connect CONNECTION_TYPE)]
    [(thermal_width WIDTH)]
    [(thermal_gap DISTANCE)]
    [ATTRIBUTES]
    [(private_layers LAYER_DEFINITIONS)]
    [(net_tie_pad_groups PAD_GROUP_DEFINITIONS)]
    GRAPHIC_ITEMS...
    PADS...
    ZONES...
    GROUPS...
    3D_MODEL
)
Parameters:
  • library_link (str | None) – Link to footprint library (optional)

  • version (KiCadInt | None) – File format version (optional)

  • generator (KiCadStr | None) – Generator application (optional)

  • generator_version (KiCadStr | None) – Generator version (optional)

  • locked (OptionalFlag | None) – Whether the footprint cannot be edited (optional)

  • placed (OptionalFlag | None) – Whether the footprint has been placed (optional)

  • layer (Layer) – Layer the footprint is placed on

  • tedit (KiCadStr | None) – Last edit timestamp (optional)

  • uuid (Uuid | None) – Unique identifier for board footprints (optional)

  • at (At | None) – Position and rotation coordinates (optional)

  • descr (KiCadStr | None) – Description of the footprint (optional)

  • tags (KiCadStr | None) – Search tags for the footprint (optional)

  • properties (List[Property] | None) – List of footprint properties (optional)

  • path (str | None) – Hierarchical path of linked schematic symbol (optional)

  • attr (Attr | None) – Footprint attributes (optional)

  • autoplace_cost90 (int | None) – Vertical cost for automatic placement (optional)

  • autoplace_cost180 (int | None) – Horizontal cost for automatic placement (optional)

  • solder_mask_margin (float | None) – Solder mask distance from pads (optional)

  • solder_paste_margin (float | None) – Solder paste distance from pads (optional)

  • solder_paste_ratio (float | None) – Percentage of pad size for solder paste (optional)

  • clearance (KiCadFloat | None) – Clearance to board copper objects (optional)

  • zone_connect (int | None) – How pads connect to filled zones (optional)

  • thermal_width (KiCadFloat | None) – Thermal relief spoke width (optional)

  • thermal_gap (KiCadFloat | None) – Distance from pad to zone for thermal relief (optional)

  • private_layers (List[str] | None) – List of private layers (optional)

  • net_tie_pad_groups (NetTiePadGroups | None) – Net tie pad groups (optional)

  • pads (List[Pad] | None) – List of pads (optional)

  • models (List[Model] | None) – List of 3D models (optional)

  • fp_elements (List[FpArc | FpCircle | FpCurve | FpLine | FpPoly | FpRect | FpText] | None) – List of footprint graphical elements (optional)

  • embedded_fonts (OptionalFlag | None) – Embedded fonts settings (optional)

  • embedded_files (EmbeddedFiles | None) – Embedded files container (optional)

__init__(library_link=None, version=<factory>, generator=<factory>, generator_version=<factory>, locked=<factory>, placed=<factory>, layer=<factory>, tedit=<factory>, uuid=None, at=None, descr=<factory>, tags=<factory>, properties=<factory>, path=None, attr=None, autoplace_cost90=None, autoplace_cost180=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_ratio=None, clearance=<factory>, zone_connect=None, thermal_width=<factory>, thermal_gap=<factory>, private_layers=<factory>, net_tie_pad_groups=None, pads=<factory>, models=<factory>, fp_elements=<factory>, embedded_fonts=<factory>, embedded_files=None)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for footprint operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_mod file format.

Parameters:
  • file_path (str) – Path to write the .kicad_mod file

  • encoding (str) – File encoding (default: utf-8)

class General(thickness=<factory>, legacy_teardrops=<factory>)[source]

Bases: KiCadObject

General board settings definition token.

The ‘general’ token defines general board settings in the format:

(general
    (thickness THICKNESS)
    [(legacy_teardrops yes|no)]
)
Parameters:
  • thickness (KiCadFloat) – Board thickness

  • legacy_teardrops (OptionalFlag | None) – Whether to use legacy teardrops (optional)

__init__(thickness=<factory>, legacy_teardrops=<factory>)
class GrText(text='', at=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>)[source]

Bases: KiCadObject

Graphical text definition token.

The ‘gr_text’ token defines text graphic objects in the format:

(gr_text
    "TEXT"
    POSITION_IDENTIFIER
    (layer LAYER_DEFINITION [knockout])
    (uuid UUID)
    (effects TEXT_EFFECTS)
)
Parameters:
  • text (str) – Text content

  • at (At) – Position and rotation coordinates

  • layer (Layer) – Layer definition

  • uuid (Uuid) – Unique identifier

  • effects (Effects) – Text effects

__init__(text='', at=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class KicadPcb(version=<factory>, generator=<factory>, generator_version=<factory>, general=None, page=<factory>, paper=<factory>, layers=None, setup=None, properties=<factory>, nets=<factory>, footprints=<factory>, gr_texts=<factory>, segments=<factory>, vias=<factory>, zones=<factory>)[source]

Bases: KiCadObject

KiCad PCB board file definition.

The ‘kicad_pcb’ token defines a complete PCB board file in the format:

(kicad_pcb
    (version VERSION)
    (generator GENERATOR)
    (general ...)
    (paper "SIZE")
    (page ...)
    (layers ...)
    (setup ...)
    [(property ...)]
    [(net ...)]
    [(footprint ...)]
    [(gr_text ...)]
    [(segment ...)]
    [(via ...)]
    [(zone ...)]
)
Parameters:
  • version (KiCadInt) – File format version

  • generator (KiCadStr) – Generator application

  • generator_version (KiCadStr | None) – Generator version (optional)

  • general (General | None) – General board settings (optional)

  • page (KiCadStr | None) – Page settings (optional)

  • paper (KiCadStr | None) – Paper size specification (optional)

  • layers (Layers | None) – Layer definitions (optional)

  • setup (Setup | None) – Board setup (optional)

  • properties (List[Property]) – Board properties

  • nets (List[Net]) – Net definitions

  • footprints (List[Footprint]) – Footprint instances

  • gr_texts (List[GrText]) – Graphical text elements

  • segments (List[Segment]) – Track segments

  • vias (List[Via]) – Via definitions

  • zones (List[Zone]) – Zone definitions

__init__(version=<factory>, generator=<factory>, generator_version=<factory>, general=None, page=<factory>, paper=<factory>, layers=None, setup=None, properties=<factory>, nets=<factory>, footprints=<factory>, gr_texts=<factory>, segments=<factory>, vias=<factory>, zones=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for PCB operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_pcb file format.

Parameters:
  • file_path (str) – Path to write the .kicad_pcb file

  • encoding (str) – File encoding (default: utf-8)

class Layer(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)[source]

Bases: KiCadObject

Layer definition token.

The ‘layer’ token defines layer information in the format:

(layer "NAME" | dielectric NUMBER (type "DESCRIPTION")
       [(color "COLOR")] [(thickness THICKNESS)]
       [(material "MATERIAL")] [(epsilon_r VALUE)]
       [(loss_tangent VALUE)])
For simple layer references:

(layer “LAYER_NAME”)

Parameters:
  • name (str) – Layer name or ‘dielectric’

  • number (int | None) – Layer stack number (optional)

  • type (str | None) – Layer type description (optional)

  • color (str | None) – Layer color as string (optional)

  • thickness (float | None) – Layer thickness value (optional)

  • material (str | None) – Material name (optional)

  • epsilon_r (float | None) – Dielectric constant value (optional)

  • loss_tangent (float | None) – Loss tangent value (optional)

__init__(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)
class Layers(layers=<factory>)[source]

Bases: KiCadObject

Layer list definition token.

The ‘layers’ token defines a list of layer names in the format:

(layers "F.Cu" "F.Paste" "F.Mask")
(layers "*.Cu" "*.Mask" "F.SilkS")

Used for pad layers, via layers, and other layer specifications.

layers

List of layer names

Type:

List[str]

Parameters:

layers (List[str]) – List of layer names

__init__(layers=<factory>)
class Net(number=0, name='')[source]

Bases: KiCadObject

Net connection definition token.

The ‘net’ token defines the net connection in the format:

(net ORDINAL "NET_NAME")
Parameters:
  • number (int) – Net number

  • name (str) – Net name

__init__(number=0, name='')
class Nets(net_definitions=<factory>)[source]

Bases: KiCadObject

Nets section definition token.

The ‘nets’ token defines nets for the board in the format:

(net
    ORDINAL
    "NET_NAME"
)
Parameters:

net_definitions (List[tuple[Any, ...]]) – List of net definitions (ordinal, net_name)

__init__(net_definitions=<factory>)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class PrivateLayers(layers=<factory>)[source]

Bases: KiCadObject

Private layers definition token.

The ‘private_layers’ token defines layers private to specific elements in the format:

(private_layers "LAYER_LIST")
Parameters:

layers (List[str]) – List of private layer names

__init__(layers=<factory>)
class Property(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)[source]

Bases: KiCadObject

Property definition token.

The ‘property’ token defines properties in two formats:

General properties::

(property “KEY” “VALUE”)

Symbol properties::
(property

“KEY” “VALUE” (id N) POSITION_IDENTIFIER TEXT_EFFECTS

)

Parameters:
  • key (str) – Property key name (must be unique)

  • value (str) – Property value

  • id (KiCadStr | None) – Property ID (optional)

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • unlocked (OptionalFlag | None) – Whether property is unlocked (optional)

  • layer (Layer | None) – Layer assignment (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • hide (OptionalFlag | None) – Hide property flag (optional)

__init__(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)
class Segment(start=<factory>, end=<factory>, width=<factory>, layer=<factory>, locked=<factory>, net=0, tstamp=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Track segment definition token.

The ‘segment’ token defines a track segment in the format:

(segment
    (start X Y)
    (end X Y)
    (width WIDTH)
    (layer LAYER_DEFINITION)
    [(locked)]
    (net NET_NUMBER)
    (tstamp UUID)
)
Parameters:
  • start (Start) – Coordinates of the beginning of the line

  • end (End) – Coordinates of the end of the line

  • width (KiCadFloat) – Line width

  • layer (Layer) – Layer the track segment resides on

  • locked (OptionalFlag | None) – Whether the line cannot be edited (optional)

  • net (int) – Net ordinal number from net section

  • tstamp (KiCadStr | None) – Unique identifier of the line object (optional)

  • uuid (Uuid | None) – Unique identifier

__init__(start=<factory>, end=<factory>, width=<factory>, layer=<factory>, locked=<factory>, net=0, tstamp=<factory>, uuid=<factory>)
class Setup(stackup=None, pad_to_mask_clearance=0.0, solder_mask_min_width=None, pad_to_paste_clearance=None, pad_to_paste_clearance_ratio=None, aux_axis_origin=None, grid_origin=None, plot_settings=None)[source]

Bases: KiCadObject

Board setup definition token.

The ‘setup’ token stores current settings and options used by the board in the format:

(setup
    [(STACK_UP_SETTINGS)]
    (pad_to_mask_clearance CLEARANCE)
    [(solder_mask_min_width MINIMUM_WIDTH)]
    [(pad_to_paste_clearance CLEARANCE)]
    [(pad_to_paste_clearance_ratio RATIO)]
    [(aux_axis_origin X Y)]
    [(grid_origin X Y)]
    (PLOT_SETTINGS)
)
Parameters:
  • stackup (dict[Any, Any] | None) – Stackup definition (optional)

  • pad_to_mask_clearance (float) – Pad to mask clearance

  • solder_mask_min_width (float | None) – Minimum solder mask width (optional)

  • pad_to_paste_clearance (float | None) – Pad to paste clearance (optional)

  • pad_to_paste_clearance_ratio (float | None) – Pad to paste clearance ratio (0-100%) (optional)

  • aux_axis_origin (tuple[float, float] | None) – Auxiliary axis origin (X, Y) (optional)

  • grid_origin (tuple[float, float] | None) – Grid origin (X, Y) (optional)

  • plot_settings (dict[Any, Any] | None) – Plot settings (optional)

__init__(stackup=None, pad_to_mask_clearance=0.0, solder_mask_min_width=None, pad_to_paste_clearance=None, pad_to_paste_clearance_ratio=None, aux_axis_origin=None, grid_origin=None, plot_settings=None)
class Start(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Start point definition token.

The ‘start’ token defines a start point in the format: (start X Y)

Parameters:
  • x (float) – Horizontal position of the start point

  • y (float) – Vertical position of the start point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Tracks(segments=<factory>)[source]

Bases: KiCadObject

Tracks container definition token.

The ‘tracks’ token defines a container for track segments in the format:

(tracks
    (segment ...)
    ...
)
Parameters:

segments (List[Segment]) – List of track segments

__init__(segments=<factory>)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class Via(type=None, locked=<factory>, at=<factory>, size=<factory>, drill=<factory>, layers=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, free=<factory>, net=0, tstamp=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Via definition token.

The ‘via’ token defines a track via in the format:

(via
    [TYPE]
    [(locked)]
    (at X Y)
    (size DIAMETER)
    (drill DIAMETER)
    (layers LAYER1 LAYER2)
    [(remove_unused_layers)]
    [(keep_end_layers)]
    [(free)]
    (net NET_NUMBER)
    (tstamp UUID)
)
Parameters:
  • type (str | None) – Via type (blind | micro) (optional)

  • locked (OptionalFlag | None) – Whether the line cannot be edited (optional)

  • at (At) – Coordinates of the center of the via

  • size (KiCadFloat) – Diameter of the via annular ring

  • drill (KiCadFloat) – Drill diameter of the via

  • layers (Layers) – Layer set the via connects

  • remove_unused_layers (OptionalFlag | None) – Remove unused layers flag (optional)

  • keep_end_layers (OptionalFlag | None) – Keep end layers flag (optional)

  • free (OptionalFlag | None) – Whether via is free to move outside assigned net (optional)

  • net (int) – Net ordinal number from net section

  • tstamp (KiCadStr | None) – Unique identifier of the line object (optional)

  • uuid (Uuid | None) – Unique identifier

__init__(type=None, locked=<factory>, at=<factory>, size=<factory>, drill=<factory>, layers=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, free=<factory>, net=0, tstamp=<factory>, uuid=<factory>)
class Vias(vias=<factory>)[source]

Bases: KiCadObject

Vias container definition token.

The ‘vias’ token defines a container for vias in the format:

(vias
    (via ...)
    ...
)
Parameters:

vias (List[Via]) – List of vias

__init__(vias=<factory>)
class Zone(hatch=<factory>, connect_pads=<factory>, fill=<factory>, polygon=<factory>, net=0, net_name='', layer='', uuid=<factory>, min_thickness=0.0, name=None, priority=None, filled_areas_thickness=<factory>, keepout=None, filled_polygons=<factory>, filled_segments=<factory>)[source]

Bases: KiCadObject

Zone definition token.

The ‘zone’ token defines a zone on the board or footprint in the format:

(zone
    (net NET_NUMBER)
    (net_name "NET_NAME")
    (layer LAYER_DEFINITION)
    (uuid UUID)
    [(name "NAME")]
    (hatch STYLE PITCH)
    [(priority PRIORITY)]
    (connect_pads [CONNECTION_TYPE] (clearance CLEARANCE))
    (min_thickness THICKNESS)
    [(filled_areas_thickness no)]
    [ZONE_KEEPOUT_SETTINGS]
    ZONE_FILL_SETTINGS
    (polygon COORDINATE_POINT_LIST)
    [ZONE_FILL_POLYGONS...]
    [ZONE_FILL_SEGMENTS...]
)
Parameters:
  • hatch (Hatch) – Hatch settings

  • connect_pads (ConnectPads) – Pad connection settings

  • fill (Fill) – Fill settings

  • polygon (Polygon) – Zone outline polygon

  • net (int) – Net number

  • net_name (str) – Net name

  • layer (str) – Layer name

  • uuid (Uuid) – Unique identifier

  • min_thickness (float) – Minimum thickness

  • name (str | None) – Zone name (optional)

  • priority (int | None) – Zone priority (optional)

  • filled_areas_thickness (OptionalFlag | None) – Filled areas thickness flag (optional)

  • keepout (Keepout | None) – Keepout settings (optional)

  • filled_polygons (List[FilledPolygon] | None) – List of fill polygons (optional)

  • filled_segments (List[FilledSegments] | None) – List of fill segments (optional)

__init__(hatch=<factory>, connect_pads=<factory>, fill=<factory>, polygon=<factory>, net=0, net_name='', layer='', uuid=<factory>, min_thickness=0.0, name=None, priority=None, filled_areas_thickness=<factory>, keepout=None, filled_polygons=<factory>, filled_segments=<factory>)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.symbol_library module

Symbol library elements for KiCad S-expressions - schematic symbol definitions.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class Arc(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Arc definition token.

The ‘arc’ token defines a graphical arc in a symbol definition in the format:

(arc
    (start X Y)
    (mid X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
    (uuid UUID)
)
Parameters:
  • start (Start) – Start point of the arc

  • mid (Mid | None) – Mid point of the arc (optional)

  • end (End) – End point of the arc

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class Bezier(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)[source]

Bases: KiCadObject

Bezier curve definition token.

The ‘bezier’ token defines a graphic Cubic Bezier curve in the format:

(bezier
    COORDINATE_POINT_LIST
    (layer LAYER_DEFINITION)
    (width WIDTH)
    (uuid UUID)
)
Parameters:
  • pts (Pts) – List of X/Y coordinates of the four points of the curve

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (Fill | None) – Fill definition for filling (optional)

  • width (KiCadFloat | None) – Line width of the curve (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)
class Circle(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Circle definition token.

The ‘circle’ token defines a graphical circle in a symbol definition in the format:

(circle
    (center X Y)
    (radius RADIUS)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • center (Center) – Center point of the circle

  • radius (KiCadFloat) – Radius length of the circle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class Effects(font=None, justify=None, hide=<factory>, href=<factory>)[source]

Bases: KiCadObject

Text effects definition token.

The ‘effects’ token defines text formatting effects in the format:

(effects
    (font [size SIZE] [thickness THICKNESS] [bold] [italic])
    [(justify JUSTIFY)]
    [hide]
)
Parameters:
  • font (Font | None) – Font definition (optional)

  • justify (Justify | None) – Text justification (optional)

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • href (KiCadStr | None) – Hyperlink reference (optional)

__init__(font=None, justify=None, hide=<factory>, href=<factory>)
class Instances(instances=<factory>)[source]

Bases: KiCadObject

Symbol instances definition token.

The ‘instances’ token defines symbol instances in a schematic in the format:

(instances
    (project "PROJECT_NAME"
        (path "/PATH" (reference "REF") (unit N) (value "VALUE") (footprint "FOOTPRINT"))
    )
)
Parameters:

instances (List[Any]) – List of instance data

__init__(instances=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class KicadSymbolLib(version=<factory>, generator=<factory>, generator_version=<factory>, symbols=<factory>)[source]

Bases: KiCadObject

KiCad symbol library file definition.

The ‘kicad_symbol_lib’ token defines a complete symbol library file in the format:

(kicad_symbol_lib
    (version VERSION)
    (generator GENERATOR)
    ;; symbol definitions...
)
Parameters:
  • version (KiCadInt) – File format version

  • generator (KiCadStr) – Generator application name

  • generator_version (KiCadStr | None) – Generator version (optional)

  • symbols (List[Symbol] | None) – List of symbol definitions (optional)

__init__(version=<factory>, generator=<factory>, generator_version=<factory>, symbols=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for symbol library operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_sym file format.

Parameters:
  • file_path (str) – Path to write the .kicad_sym file

  • encoding (str) – File encoding (default: utf-8)

class LibSymbols(symbols=<factory>)[source]

Bases: KiCadObject

Library symbols container token.

The ‘lib_symbols’ token defines a symbol library containing all symbols used in the schematic in the format:

(lib_symbols
    SYMBOL_DEFINITIONS...
)
Parameters:

symbols (List[Symbol]) – List of symbols

__init__(symbols=<factory>)
class Line(start=<factory>, end=<factory>, uuid=None)[source]

Bases: KiCadObject

Line definition token.

The ‘line’ token defines a basic line geometry in the format:

(line (start X Y) (end X Y) (uuid UUID))
Parameters:
  • start (Start) – Start point of the line

  • end (End) – End point of the line

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, uuid=None)
class Number(number='', effects=None)[source]

Bases: KiCadObject

Pin number definition token.

The ‘number’ token defines a pin number with text effects in the format:

(number "NUMBER" TEXT_EFFECTS)
Parameters:
  • number (str) – Pin number string

  • effects (Effects | None) – Text effects (optional)

__init__(number='', effects=None)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class Pin(electrical_type=PinElectricalType.PASSIVE, graphic_style=PinGraphicStyle.LINE, at=<factory>, length=<factory>, name=None, number=None, hide=<factory>)[source]

Bases: KiCadObject

Symbol pin definition token.

The ‘pin’ token defines a symbol pin in the format:

(pin
    PIN_ELECTRICAL_TYPE
    PIN_GRAPHIC_STYLE
    POSITION_IDENTIFIER
    (length LENGTH)
    (name "NAME" TEXT_EFFECTS)
    (number "NUMBER" TEXT_EFFECTS)
)
Parameters:
__init__(electrical_type=PinElectricalType.PASSIVE, graphic_style=PinGraphicStyle.LINE, at=<factory>, length=<factory>, name=None, number=None, hide=<factory>)
class PinElectricalType(*values)[source]

Bases: Enum

Pin electrical types for symbols.

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'
TRI_STATE = 'tri_state'
UNSPECIFIED = 'unspecified'
class PinGraphicStyle(*values)[source]

Bases: Enum

Pin graphical styles for symbols.

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 PinName(name='', effects=None)[source]

Bases: KiCadObject

Pin name definition token.

The ‘name’ token defines a pin name with text effects in the format:

(name "NAME" TEXT_EFFECTS)
Parameters:
  • name (str) – Pin name string

  • effects (Effects | None) – Text effects (optional)

__init__(name='', effects=None)
class PinNames(offset=None, hide=<factory>)[source]

Bases: KiCadObject

Pin names attributes definition token.

The ‘pin_names’ token defines attributes for all pin names of a symbol in the format:

(pin_names [(offset OFFSET)] [hide])
Parameters:
  • offset (float | None) – Pin name offset (optional)

  • hide (OptionalFlag | None) – Whether pin names are hidden (optional)

__init__(offset=None, hide=<factory>)
class PinNumbers(hide=<factory>)[source]

Bases: KiCadObject

Pin numbers visibility definition token.

The ‘pin_numbers’ token defines visibility of pin numbers for a symbol in the format:

(pin_numbers [hide])
Parameters:

hide (OptionalFlag | None) – Whether pin numbers are hidden (optional)

__init__(hide=<factory>)
class Pintype(type=PinElectricalType.PASSIVE)[source]

Bases: KiCadObject

Pin type definition token.

The ‘pintype’ token defines the electrical type for a pin in the format:

(pintype "TYPE")

Where TYPE can be: input, output, bidirectional, tri_state, passive, free, unspecified, power_in, power_out, open_collector, open_emitter, no_connect

Parameters:

type (PinElectricalType) – Pin electrical type

__init__(type=PinElectricalType.PASSIVE)
class Polygon(pts=<factory>, uuid=None)[source]

Bases: KiCadObject

Polygon definition token.

The ‘polygon’ token defines a polygon with multiple points in the format:

(polygon (pts (xy X Y) (xy X Y) ...) (uuid UUID))
Parameters:
  • pts (Pts) – Polygon vertex points

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, uuid=None)
class Polyline(pts=<factory>, stroke=None, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Polyline definition token.

The ‘polyline’ token defines a connected series of line segments in the format:

(polyline
    (pts (xy X Y) (xy X Y) ...)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • pts (Pts) – Polyline connection points

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=<factory>, uuid=None)
class Property(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)[source]

Bases: KiCadObject

Property definition token.

The ‘property’ token defines properties in two formats:

General properties::

(property “KEY” “VALUE”)

Symbol properties::
(property

“KEY” “VALUE” (id N) POSITION_IDENTIFIER TEXT_EFFECTS

)

Parameters:
  • key (str) – Property key name (must be unique)

  • value (str) – Property value

  • id (KiCadStr | None) – Property ID (optional)

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • unlocked (OptionalFlag | None) – Whether property is unlocked (optional)

  • layer (Layer | None) – Layer assignment (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • hide (OptionalFlag | None) – Hide property flag (optional)

__init__(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)
class Rectangle(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Rectangle definition token (symbol form).

The ‘rectangle’ token defines a graphical rectangle in a symbol definition in the format:

(rectangle
    (start X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • start (Start) – Start point of the rectangle

  • end (End) – End point of the rectangle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class Symbol(library_id='', extends=None, pin_numbers=None, pin_names=None, in_bom=<factory>, on_board=<factory>, exclude_from_sim=<factory>, embedded_fonts=<factory>, power=<factory>, properties=<factory>, graphic_items=<factory>, text=<factory>, pins=<factory>, units=<factory>, unit_name=None)[source]

Bases: KiCadObject

Symbol definition token.

The ‘symbol’ token defines a complete schematic symbol in the format:

(symbol "LIBRARY_ID"
    [(extends "LIBRARY_ID")]
    [(pin_numbers hide)]
    [(pin_names [(offset OFFSET)] hide)]
    (in_bom yes | no)
    (on_board yes | no)
    SYMBOL_PROPERTIES...
    GRAPHIC_ITEMS...
    PINS...
    UNITS...
    [(unit_name "UNIT_NAME")]
)
Parameters:
  • library_id (str) – Unique library identifier or unit ID

  • extends (str | None) – Parent library ID for derived symbols (optional)

  • pin_numbers (PinNumbers | None) – Pin numbers visibility settings (optional)

  • pin_names (PinNames | None) – Pin names attributes (optional)

  • in_bom (OptionalFlag | None) – Whether symbol appears in BOM (optional)

  • on_board (OptionalFlag | None) – Whether symbol is exported to PCB (yes/no) (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether symbol is excluded from simulation (optional)

  • embedded_fonts (OptionalFlag | None) – Whether embedded fonts are used (optional)

  • power (OptionalFlag | None) – Whether symbol is a power symbol (optional)

  • properties (List[Property] | None) – List of symbol properties (optional)

  • graphic_items (List[Arc | Bezier | Circle | Line | Polygon | Polyline | Rectangle] | None) – List of graphical items (optional)

  • text (List[Text] | None) – List of text elements (optional)

  • pins (List[Pin] | None) – List of symbol pins (optional)

  • units (List[Symbol] | None) – List of child symbol units (optional)

  • unit_name (str | None) – Display name for subunits (optional)

__init__(library_id='', extends=None, pin_numbers=None, pin_names=None, in_bom=<factory>, on_board=<factory>, exclude_from_sim=<factory>, embedded_fonts=<factory>, power=<factory>, properties=<factory>, graphic_items=<factory>, text=<factory>, pins=<factory>, units=<factory>, unit_name=None)
class Text(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)[source]

Bases: KiCadObject

Text content definition token.

The ‘text’ token defines text content in the format: (text “TEXT_CONTENT”

(at X Y [ANGLE]) (effects EFFECTS)

)

Parameters:
  • content (str) – Text content

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether to exclude from simulation (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.footprint_library module

Footprint library elements for KiCad S-expressions - footprint management and properties.

class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class Attr(type='', board_only=<factory>, exclude_from_pos_files=<factory>, exclude_from_bom=<factory>)[source]

Bases: KiCadObject

Footprint attributes definition token.

The ‘attr’ token defines footprint attributes in the format:

(attr
    TYPE
    [board_only]
    [exclude_from_pos_files]
    [exclude_from_bom]
)
Parameters:
  • type (str) – Footprint type (smd | through_hole)

  • board_only (OptionalFlag | None) – Whether footprint is only defined in board (optional)

  • exclude_from_pos_files (OptionalFlag | None) – Whether to exclude from position files (optional)

  • exclude_from_bom (OptionalFlag | None) – Whether to exclude from BOM files (optional)

__init__(type='', board_only=<factory>, exclude_from_pos_files=<factory>, exclude_from_bom=<factory>)
class EmbeddedFile(name=<factory>, type=<factory>, data=None, checksum=<factory>)[source]

Bases: KiCadObject

Embedded file definition token.

The ‘file’ token defines an embedded file in the format:

(file
    (name "FILENAME")
    (type TYPE)
    [(data |DATA|)]
    [(checksum "CHECKSUM")]
)
Parameters:
  • name (KiCadStr) – File name token

  • type (KiCadStr) – File type token

  • data (FileData | None) – Base64 encoded file data token (optional)

  • checksum (KiCadStr | None) – File checksum token (optional)

__init__(name=<factory>, type=<factory>, data=None, checksum=<factory>)
class EmbeddedFiles(files=<factory>)[source]

Bases: KiCadObject

Embedded files container definition token.

The ‘embedded_files’ token defines a container for embedded files in the format:

(embedded_files
    (file ...)
    ...
)
Parameters:

files (List[EmbeddedFile]) – List of embedded files

__init__(files=<factory>)
class FileData(lines=<factory>)[source]

Bases: KiCadObject

Data definition token for embedded files.

The ‘data’ token defines base64 encoded file data in the format:

(data |DATA_LINE1|
      |DATA_LINE2|
      ...)
Parameters:

lines (List[str]) – List of base64 encoded data lines

__init__(lines=<factory>)
class Footprint(library_link=None, version=<factory>, generator=<factory>, generator_version=<factory>, locked=<factory>, placed=<factory>, layer=<factory>, tedit=<factory>, uuid=None, at=None, descr=<factory>, tags=<factory>, properties=<factory>, path=None, attr=None, autoplace_cost90=None, autoplace_cost180=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_ratio=None, clearance=<factory>, zone_connect=None, thermal_width=<factory>, thermal_gap=<factory>, private_layers=<factory>, net_tie_pad_groups=None, pads=<factory>, models=<factory>, fp_elements=<factory>, embedded_fonts=<factory>, embedded_files=None)[source]

Bases: KiCadObject

Footprint definition token that defines a complete footprint.

The ‘footprint’ token defines a footprint with all its elements in the format:

(footprint
    ["LIBRARY_LINK"]
    [locked]
    [placed]
    (layer LAYER_DEFINITIONS)
    (tedit TIME_STAMP)
    [(uuid UUID)]
    [POSITION_IDENTIFIER]
    [(descr "DESCRIPTION")]
    [(tags "NAME")]
    [(property "KEY" "VALUE") ...]
    (path "PATH")
    [(autoplace_cost90 COST)]
    [(autoplace_cost180 COST)]
    [(solder_mask_margin MARGIN)]
    [(solder_paste_margin MARGIN)]
    [(solder_paste_ratio RATIO)]
    [(clearance CLEARANCE)]
    [(zone_connect CONNECTION_TYPE)]
    [(thermal_width WIDTH)]
    [(thermal_gap DISTANCE)]
    [ATTRIBUTES]
    [(private_layers LAYER_DEFINITIONS)]
    [(net_tie_pad_groups PAD_GROUP_DEFINITIONS)]
    GRAPHIC_ITEMS...
    PADS...
    ZONES...
    GROUPS...
    3D_MODEL
)
Parameters:
  • library_link (str | None) – Link to footprint library (optional)

  • version (KiCadInt | None) – File format version (optional)

  • generator (KiCadStr | None) – Generator application (optional)

  • generator_version (KiCadStr | None) – Generator version (optional)

  • locked (OptionalFlag | None) – Whether the footprint cannot be edited (optional)

  • placed (OptionalFlag | None) – Whether the footprint has been placed (optional)

  • layer (Layer) – Layer the footprint is placed on

  • tedit (KiCadStr | None) – Last edit timestamp (optional)

  • uuid (Uuid | None) – Unique identifier for board footprints (optional)

  • at (At | None) – Position and rotation coordinates (optional)

  • descr (KiCadStr | None) – Description of the footprint (optional)

  • tags (KiCadStr | None) – Search tags for the footprint (optional)

  • properties (List[Property] | None) – List of footprint properties (optional)

  • path (str | None) – Hierarchical path of linked schematic symbol (optional)

  • attr (Attr | None) – Footprint attributes (optional)

  • autoplace_cost90 (int | None) – Vertical cost for automatic placement (optional)

  • autoplace_cost180 (int | None) – Horizontal cost for automatic placement (optional)

  • solder_mask_margin (float | None) – Solder mask distance from pads (optional)

  • solder_paste_margin (float | None) – Solder paste distance from pads (optional)

  • solder_paste_ratio (float | None) – Percentage of pad size for solder paste (optional)

  • clearance (KiCadFloat | None) – Clearance to board copper objects (optional)

  • zone_connect (int | None) – How pads connect to filled zones (optional)

  • thermal_width (KiCadFloat | None) – Thermal relief spoke width (optional)

  • thermal_gap (KiCadFloat | None) – Distance from pad to zone for thermal relief (optional)

  • private_layers (List[str] | None) – List of private layers (optional)

  • net_tie_pad_groups (NetTiePadGroups | None) – Net tie pad groups (optional)

  • pads (List[Pad] | None) – List of pads (optional)

  • models (List[Model] | None) – List of 3D models (optional)

  • fp_elements (List[FpArc | FpCircle | FpCurve | FpLine | FpPoly | FpRect | FpText] | None) – List of footprint graphical elements (optional)

  • embedded_fonts (OptionalFlag | None) – Embedded fonts settings (optional)

  • embedded_files (EmbeddedFiles | None) – Embedded files container (optional)

__init__(library_link=None, version=<factory>, generator=<factory>, generator_version=<factory>, locked=<factory>, placed=<factory>, layer=<factory>, tedit=<factory>, uuid=None, at=None, descr=<factory>, tags=<factory>, properties=<factory>, path=None, attr=None, autoplace_cost90=None, autoplace_cost180=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_ratio=None, clearance=<factory>, zone_connect=None, thermal_width=<factory>, thermal_gap=<factory>, private_layers=<factory>, net_tie_pad_groups=None, pads=<factory>, models=<factory>, fp_elements=<factory>, embedded_fonts=<factory>, embedded_files=None)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for footprint operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_mod file format.

Parameters:
  • file_path (str) – Path to write the .kicad_mod file

  • encoding (str) – File encoding (default: utf-8)

class Footprints(footprints=<factory>)[source]

Bases: KiCadObject

Footprints container token.

The ‘footprints’ token defines a container for multiple footprints in the format:

(footprints
    (footprint ...)
    ...
)
Parameters:

footprints (List[Footprint]) – List of footprints

__init__(footprints=<factory>)
class FpArc(start=<factory>, mid=None, end=<factory>, layer=<factory>, width=<factory>, stroke=None, locked=<factory>, angle=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint arc definition token.

The ‘fp_arc’ token defines an arc in a footprint in the format:

(fp_arc
    (start X Y)
    [(mid X Y)]
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    [STROKE_DEFINITION]
    [(locked)]
    [(uuid UUID)]
    [(angle ANGLE)]
)
Parameters:
  • start (Start) – Start point coordinates

  • mid (Pos | None) – Mid point coordinates (optional)

  • end (End) – End point coordinates

  • layer (Layer | None) – Layer definition

  • width (KiCadFloat | None) – Line width (prior to version 7)

  • stroke (Stroke | None) – Stroke definition (from version 7) (optional)

  • locked (OptionalFlag | None) – Whether the arc is locked (optional)

  • angle (KiCadFloat | None) – Arc angle in degrees (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, mid=None, end=<factory>, layer=<factory>, width=<factory>, stroke=None, locked=<factory>, angle=<factory>, uuid=None)
class FpCircle(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, fill=<factory>, locked=<factory>)[source]

Bases: KiCadObject

Footprint circle definition token.

The ‘fp_circle’ token defines a circle in a footprint in the format:

(fp_circle
    (center X Y)
    (end X Y)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • center (Center) – Center point

  • end (End) – End point

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • locked (OptionalFlag | None) – Whether the circle is locked (optional)

__init__(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, fill=<factory>, locked=<factory>)
class FpCurve(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)[source]

Bases: KiCadObject

Footprint curve definition token.

The ‘fp_curve’ token defines a Bezier curve in a footprint in the format:

(fp_curve
    (pts (xy X Y) (xy X Y) (xy X Y) (xy X Y))
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • pts (Pts) – Control points

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • locked (OptionalFlag | None) – Whether the curve is locked (optional)

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)
class FpLine(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)[source]

Bases: KiCadObject

Footprint line definition token.

The ‘fp_line’ token defines a line in a footprint in the format:

(fp_line
    (start X Y)
    (end X Y)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • start (Start) – Start point

  • end (End) – End point

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • locked (OptionalFlag | None) – Whether the line is locked (optional)

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)
class FpPoly(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint polygon definition token.

The ‘fp_poly’ token defines a polygon in a footprint in the format:

(fp_poly
    (pts (xy X Y) ...)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • pts (Pts) – Polygon points

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • locked (OptionalFlag | None) – Whether thepolygon is locked (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)
class FpRect(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Footprint rectangle definition token.

The ‘fp_rect’ token defines a graphic rectangle in a footprint definition in the format:

(fp_rect
    (start X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    STROKE_DEFINITION
    [(fill yes | no)]
    [(locked)]
    (uuid UUID)
)
Parameters:
  • start (Start) – Coordinates of the upper left corner

  • end (End) – Coordinates of the lower right corner

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (prior to version 7) (optional)

  • stroke (Stroke | None) – Stroke definition (from version 7) (optional)

  • fill (OptionalFlag | None) – Whether the rectangle is filled (yes/no) (optional)

  • locked (OptionalFlag | None) – Whether the rectangle cannot be edited (optional)

  • uuid (Uuid) – Unique identifier

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)
class FpText(type='', text='', at=<factory>, unlocked=<factory>, layer=<factory>, hide=<factory>, effects=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint text definition token.

The ‘fp_text’ token defines text in a footprint in the format:

(fp_text
    TYPE
    "TEXT"
    POSITION_IDENTIFIER
    [unlocked]
    (layer LAYER_DEFINITION)
    [hide]
    (effects TEXT_EFFECTS)
    (uuid UUID)
)
Parameters:
  • type (str) – Text type (reference | value | user)

  • text (str) – Text content

  • at (FpTextAt) – Position and rotation coordinates

  • unlocked (OptionalFlag | None) – Whether text orientation can be other than upright (optional)

  • layer (Layer) – Layer definition

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • effects (Effects) – Text effects

  • uuid (Uuid | None) – Unique identifier

__init__(type='', text='', at=<factory>, unlocked=<factory>, layer=<factory>, hide=<factory>, effects=<factory>, uuid=None)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class Layer(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)[source]

Bases: KiCadObject

Layer definition token.

The ‘layer’ token defines layer information in the format:

(layer "NAME" | dielectric NUMBER (type "DESCRIPTION")
       [(color "COLOR")] [(thickness THICKNESS)]
       [(material "MATERIAL")] [(epsilon_r VALUE)]
       [(loss_tangent VALUE)])
For simple layer references:

(layer “LAYER_NAME”)

Parameters:
  • name (str) – Layer name or ‘dielectric’

  • number (int | None) – Layer stack number (optional)

  • type (str | None) – Layer type description (optional)

  • color (str | None) – Layer color as string (optional)

  • thickness (float | None) – Layer thickness value (optional)

  • material (str | None) – Material name (optional)

  • epsilon_r (float | None) – Dielectric constant value (optional)

  • loss_tangent (float | None) – Loss tangent value (optional)

__init__(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)
class Model(path='', at=None, scale=None, rotate=None, offset=None)[source]

Bases: KiCadObject

3D model definition token for footprints.

The ‘model’ token defines a 3D model associated with a footprint in the format:

(model
    "3D_MODEL_FILE"
    (at (xyz X Y Z))
    (scale (xyz X Y Z))
    (rotate (xyz X Y Z))
)
Parameters:
  • path (str) – Path and file name of the 3D model

  • at (ModelAt | None) – 3D position coordinates relative to the footprint (optional)

  • scale (ModelScale | None) – Model scale factor for each 3D axis (optional)

  • rotate (ModelRotate | None) – Model rotation for each 3D axis relative to the footprint (optional)

  • offset (ModelOffset | None) – Model offset coordinates (optional)

__init__(path='', at=None, scale=None, rotate=None, offset=None)
class ModelAt(xyz=<factory>)[source]

Bases: KiCadObject

3D model position definition token.

The ‘at’ token for 3D models in the format: (at (xyz X Y Z))

Parameters:

xyz (Xyz) – 3D coordinates for model position

__init__(xyz=<factory>)
class ModelOffset(xyz=<factory>)[source]

Bases: KiCadObject

3D model offset definition token.

The ‘offset’ token for 3D models in the format: (offset (xyz X Y Z))

Parameters:

xyz (Xyz) – 3D offset coordinates for model

__init__(xyz=<factory>)
class ModelRotate(xyz=<factory>)[source]

Bases: KiCadObject

3D model rotation definition token.

The ‘rotate’ token for 3D models in the format: (rotate (xyz X Y Z))

Parameters:

xyz (Xyz) – 3D rotation angles for model

__init__(xyz=<factory>)
class ModelScale(xyz=<factory>)[source]

Bases: KiCadObject

3D model scale definition token.

The ‘scale’ token for 3D models in the format: (scale (xyz X Y Z))

Parameters:

xyz (Xyz) – 3D scale factors for model

__init__(xyz=<factory>)
class NetTiePadGroups(groups=<factory>)[source]

Bases: KiCadObject

Net tie pad groups definition token.

The ‘net_tie_pad_groups’ token defines groups of pads that are connected in the format:

(net_tie_pad_groups "PAD_LIST" "PAD_LIST" ...)
Parameters:

groups (List[str]) – List of pad group strings

__init__(groups=<factory>)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Pad(number='', type=PadType.THRU_HOLE, shape=PadShape.CIRCLE, at=<factory>, size=<factory>, layers=<factory>, drill=None, property=None, locked=<factory>, remove_unused_layer=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, roundrect_rratio=<factory>, chamfer_ratio=None, chamfer=<factory>, net=None, uuid=None, pinfunction=None, pintype=None, die_length=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_margin_ratio=None, clearance=None, zone_connect=None, thermal_width=None, thermal_gap=None, options=None, primitives=None, teardrops=None)[source]

Bases: KiCadObject

Footprint pad definition token.

The ‘pad’ token defines a pad in a footprint with comprehensive properties in the format:

(pad "NUMBER" TYPE SHAPE POSITION_IDENTIFIER [(locked)] (size X Y)
     [(drill DRILL_DEFINITION)] (layers "CANONICAL_LAYER_LIST") ...)

Note

Field order follows KiCad documentation, not dataclass conventions. Required fields after optional fields violate dataclass ordering.

Parameters:
  • number (str) – Pad number or name

  • type (PadType) – Pad type

  • shape (PadShape) – Pad shape

  • at (AtXY) – Position and rotation

  • size (Size) – Pad dimensions

  • layers (Layers) – Layer list

  • drill (Drill | None) – Drill definition (optional)

  • property (str | None) – Pad property (optional)

  • locked (OptionalFlag | None) – Whether pad is locked (optional)

  • remove_unused_layer (OptionalFlag | None) – Remove unused layers flag (optional)

  • remove_unused_layers (OptionalFlag | None) – Remove unused layers flag (newer format) (optional)

  • keep_end_layers (OptionalFlag | None) – Keep end layers flag (optional)

  • roundrect_rratio (KiCadFloat | None) – Round rectangle corner ratio (optional)

  • chamfer_ratio (float | None) – Chamfer ratio (optional)

  • chamfer (List[str] | None) – Chamfer corners (optional)

  • net (Net | None) – Net connection (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • pinfunction (str | None) – Pin function name (optional)

  • pintype (str | None) – Pin type (optional)

  • die_length (float | None) – Die length (optional)

  • solder_mask_margin (float | None) – Solder mask margin (optional)

  • solder_paste_margin (float | None) – Solder paste margin (optional)

  • solder_paste_margin_ratio (float | None) – Solder paste margin ratio (optional)

  • clearance (float | None) – Clearance value (optional)

  • zone_connect (ZoneConnection | None) – Zone connection type (optional)

  • thermal_width (float | None) – Thermal width (optional)

  • thermal_gap (float | None) – Thermal gap (optional)

  • options (Options | None) – Custom pad options (optional)

  • primitives (Primitives | None) – Custom pad primitives (optional)

  • teardrops (Teardrops | None) – Teardrop settings (optional)

__init__(number='', type=PadType.THRU_HOLE, shape=PadShape.CIRCLE, at=<factory>, size=<factory>, layers=<factory>, drill=None, property=None, locked=<factory>, remove_unused_layer=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, roundrect_rratio=<factory>, chamfer_ratio=None, chamfer=<factory>, net=None, uuid=None, pinfunction=None, pintype=None, die_length=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_margin_ratio=None, clearance=None, zone_connect=None, thermal_width=None, thermal_gap=None, options=None, primitives=None, teardrops=None)
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class Property(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)[source]

Bases: KiCadObject

Property definition token.

The ‘property’ token defines properties in two formats:

General properties::

(property “KEY” “VALUE”)

Symbol properties::
(property

“KEY” “VALUE” (id N) POSITION_IDENTIFIER TEXT_EFFECTS

)

Parameters:
  • key (str) – Property key name (must be unique)

  • value (str) – Property value

  • id (KiCadStr | None) – Property ID (optional)

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • unlocked (OptionalFlag | None) – Whether property is unlocked (optional)

  • layer (Layer | None) – Layer assignment (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • hide (OptionalFlag | None) – Hide property flag (optional)

__init__(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class Xyz(x=0.0, y=0.0, z=0.0)[source]

Bases: KiCadObject

3D coordinate definition token.

The ‘xyz’ token defines 3D coordinates in the format: (xyz X Y Z)

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

  • z (float) – Z coordinate

__init__(x=0.0, y=0.0, z=0.0)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.schematic_system module

Schematic system elements for KiCad S-expressions - schematic drawing and connectivity.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class Arc(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Arc definition token.

The ‘arc’ token defines a graphical arc in a symbol definition in the format:

(arc
    (start X Y)
    (mid X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
    (uuid UUID)
)
Parameters:
  • start (Start) – Start point of the arc

  • mid (Mid | None) – Mid point of the arc (optional)

  • end (End) – End point of the arc

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class AtXY(x=0.0, y=0.0)[source]

Bases: KiCadObject

Position identifier token for elements that only use X and Y coordinates.

The ‘at’ token defines positional coordinates in the format:

(at X Y)

Used for elements like junctions that don’t have rotation.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

__init__(x=0.0, y=0.0)
class Bezier(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)[source]

Bases: KiCadObject

Bezier curve definition token.

The ‘bezier’ token defines a graphic Cubic Bezier curve in the format:

(bezier
    COORDINATE_POINT_LIST
    (layer LAYER_DEFINITION)
    (width WIDTH)
    (uuid UUID)
)
Parameters:
  • pts (Pts) – List of X/Y coordinates of the four points of the curve

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (Fill | None) – Fill definition for filling (optional)

  • width (KiCadFloat | None) – Line width of the curve (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)
class Bus(pts=<factory>, stroke=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Bus definition token.

The ‘bus’ token defines buses in the schematic in the format:

(bus
    COORDINATE_POINT_LIST
    STROKE_DEFINITION
    UNIQUE_IDENTIFIER
)
Parameters:
  • pts (Pts) – Bus connection points

  • stroke (Stroke) – Stroke definition

  • uuid (Uuid) – Unique identifier

__init__(pts=<factory>, stroke=<factory>, uuid=<factory>)
class BusEntry(at=<factory>, size=<factory>, stroke=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Bus entry definition token.

The ‘bus_entry’ token defines a bus entry in the schematic in the format:

(bus_entry
    POSITION_IDENTIFIER
    (size X Y)
    STROKE_DEFINITION
    UNIQUE_IDENTIFIER
)
Parameters:
  • at (AtXY) – Position

  • size (Size) – Entry size

  • stroke (Stroke) – Stroke definition

  • uuid (Uuid) – Unique identifier

__init__(at=<factory>, size=<factory>, stroke=<factory>, uuid=<factory>)
class Cells(cells=<factory>)[source]

Bases: KiCadObject

Table cells container token.

The ‘cells’ token contains a list of table_cell objects in the format::
(cells

(table_cell …) (table_cell …) …

)

Parameters:

cells (List[TableCell]) – List of table cell objects

__init__(cells=<factory>)
class Circle(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Circle definition token.

The ‘circle’ token defines a graphical circle in a symbol definition in the format:

(circle
    (center X Y)
    (radius RADIUS)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • center (Center) – Center point of the circle

  • radius (KiCadFloat) – Radius length of the circle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class Color(r=0, g=0, b=0, a=0)[source]

Bases: KiCadObject

Color definition token.

The ‘color’ token defines color values in the format:

(color R G B A)
Parameters:
  • r (int) – Red color component (0-255)

  • g (int) – Green color component (0-255)

  • b (int) – Blue color component (0-255)

  • a (int) – Alpha component (0-255)

__init__(r=0, g=0, b=0, a=0)
class ColumnWidths(widths=<factory>)[source]

Bases: KiCadObject

Column widths definition token.

The ‘column_widths’ token defines column width values in the format::

(column_widths WIDTH1 WIDTH2 …)

Parameters:

widths (List[float]) – List of column width values

__init__(widths=<factory>)
class Effects(font=None, justify=None, hide=<factory>, href=<factory>)[source]

Bases: KiCadObject

Text effects definition token.

The ‘effects’ token defines text formatting effects in the format:

(effects
    (font [size SIZE] [thickness THICKNESS] [bold] [italic])
    [(justify JUSTIFY)]
    [hide]
)
Parameters:
  • font (Font | None) – Font definition (optional)

  • justify (Justify | None) – Text justification (optional)

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • href (KiCadStr | None) – Hyperlink reference (optional)

__init__(font=None, justify=None, hide=<factory>, href=<factory>)
class Fill(type=None, color=None)[source]

Bases: KiCadObject

Fill definition token.

The ‘fill’ token defines how schematic and symbol library graphical items are filled in the format: (fill

(type none | outline | background) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • type (Type | None) – Fill type specification (optional)

  • color (Color | None) – Fill color specification (optional)

__init__(type=None, color=None)
class GlobalLabel(text='', shape=None, fields_autoplaced=<factory>, at=<factory>, effects=None, uuid=<factory>, properties=<factory>)[source]

Bases: KiCadObject

Global label definition token.

The ‘global_label’ token defines a label visible across all schematics in the format:

(global_label
    "TEXT"
    (shape SHAPE)
    [(fields_autoplaced)]
    POSITION_IDENTIFIER
    TEXT_EFFECTS
    UNIQUE_IDENTIFIER
    PROPERTIES
)
Parameters:
  • text (str) – Global label text

  • shape (str | None) – Way the global label is drawn (optional)

  • fields_autoplaced (OptionalFlag | None) – Whether properties are placed automatically (optional)

  • at (At) – X and Y coordinates and rotation angle

  • effects (Effects | None) – How the global label text is drawn (optional)

  • uuid (Uuid) – Universally unique identifier

  • properties (List[Property] | None) – Properties of the global label (optional)

__init__(text='', shape=None, fields_autoplaced=<factory>, at=<factory>, effects=None, uuid=<factory>, properties=<factory>)
class HierarchicalLabel(text='', shape=None, at=None, effects=None, uuid=None)[source]

Bases: KiCadObject

Hierarchical label definition token.

The ‘hierarchical_label’ token defines hierarchical labels in schematics.

Parameters:
  • text (str) – Label text

  • shape (LabelShape | None) – Label shape (optional)

  • at (At | None) – Position (optional)

  • effects (Effects | None) – Text effects (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(text='', shape=None, at=None, effects=None, uuid=None)
class Image(at=<factory>, scale=<factory>, uuid=None, data=None, locked=<factory>)[source]

Bases: KiCadObject

Image definition token.

The ‘image’ token defines an image object in PCB files in the format:

(image (at X Y) (scale FACTOR) (uuid UUID) (data ...))
Parameters:
  • at (AtXY) – Position

  • scale (KiCadFloat | None) – Scale factor (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • data (Data | None) – Image data (optional)

  • locked (OptionalFlag | None) – Whether image is locked (optional)

__init__(at=<factory>, scale=<factory>, uuid=None, data=None, locked=<factory>)
class Junction(at=<factory>, diameter=<factory>, color=None, uuid=<factory>)[source]

Bases: KiCadObject

Junction definition token.

The ‘junction’ token defines a junction in the schematic in the format:

(junction
    POSITION_IDENTIFIER
    (diameter DIAMETER)
    (color R G B A)
    UNIQUE_IDENTIFIER
)
Parameters:
  • at (AtXY) – Position

  • diameter (KiCadFloat) – Junction diameter

  • color (Color | None) – Junction color (optional)

  • uuid (Uuid) – Unique identifier

__init__(at=<factory>, diameter=<factory>, color=None, uuid=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class KicadSch(version=<factory>, generator=<factory>, generator_version=<factory>, uuid=<factory>, paper=None, title_block=None, sheet_instances=None, embedded_fonts=<factory>, lib_symbols=None, junctions=<factory>, no_connects=<factory>, bus_entries=<factory>, wires=<factory>, buses=<factory>, labels=<factory>, global_labels=<factory>, sheets=<factory>, instances=<factory>, graphic_items=<factory>, tables=<factory>, hierarchical_labels=<factory>, rule_areas=<factory>, netclass_flags=<factory>, symbols=<factory>, text=<factory>, images=<factory>)[source]

Bases: KiCadObject

KiCad schematic file definition.

The ‘kicad_sch’ token defines a complete schematic file in the format:

(kicad_sch
    (version VERSION)
    (generator GENERATOR)
    (uuid UNIQUE_IDENTIFIER)
    (lib_symbols ...)
    ;; schematic elements...
)
Parameters:
  • version (KiCadInt) – File format version

  • generator (KiCadStr) – Generator application name

  • generator_version (KiCadStr | None) – Generator version (optional)

  • uuid (Uuid) – Universally unique identifier for the schematic

  • paper (Paper | None) – Paper settings (optional)

  • title_block (TitleBlock | None) – Title block (optional)

  • sheet_instances (SheetInstances | None) – Sheet instances (optional)

  • embedded_fonts (OptionalFlag | None) – Embedded fonts setting (optional)

  • lib_symbols (LibSymbols | None) – Symbol library container (optional)

  • junctions (List[Junction] | None) – List of junctions (optional)

  • no_connects (List[NoConnect] | None) – List of no connect markers (optional)

  • bus_entries (List[BusEntry] | None) – List of bus entries (optional)

  • wires (List[Wire] | None) – List of wires (optional)

  • buses (List[Bus] | None) – List of buses (optional)

  • labels (List[Label] | None) – List of labels (optional)

  • global_labels (List[GlobalLabel] | None) – List of global labels (optional)

  • sheets (List[Sheet] | None) – List of hierarchical sheets (optional)

  • instances (List[Any] | None) – List of symbol instances (optional)

  • graphic_items (List[Arc | Bezier | Circle | Line | Polygon | Polyline | Rectangle] | None) – List of graphical items (optional)

  • tables (List[Table] | None) – List of tables (optional)

  • hierarchical_labels (List[HierarchicalLabel] | None) – List of hierarchical labels (optional)

  • rule_areas (List[RuleArea] | None) – List of rule areas (optional)

  • netclass_flags (List[NetclassFlag] | None) – List of netclass flags (optional)

  • symbols (List[SchematicSymbol] | None) – List of symbol instances (optional)

  • text (List[Text] | None) – List of text elements (optional)

  • images (List[Image] | None) – List of image elements (optional)

__init__(version=<factory>, generator=<factory>, generator_version=<factory>, uuid=<factory>, paper=None, title_block=None, sheet_instances=None, embedded_fonts=<factory>, lib_symbols=None, junctions=<factory>, no_connects=<factory>, bus_entries=<factory>, wires=<factory>, buses=<factory>, labels=<factory>, global_labels=<factory>, sheets=<factory>, instances=<factory>, graphic_items=<factory>, tables=<factory>, hierarchical_labels=<factory>, rule_areas=<factory>, netclass_flags=<factory>, symbols=<factory>, text=<factory>, images=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for schematic operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_sch file format.

Parameters:
  • file_path (str) – Path to write the .kicad_sch file

  • encoding (str) – File encoding (default: utf-8)

class Label(text='', at=<factory>, fields_autoplaced=<factory>, effects=None, uuid=<factory>)[source]

Bases: KiCadObject

Local label definition token.

The ‘label’ token defines a local label in the format:

(label
    "TEXT"
    (at X Y ANGLE)
    (fields_autoplaced)
    (effects EFFECTS)
    (uuid UUID)
)
Parameters:
  • text (str) – Label text

  • at (At) – Position and rotation

  • fields_autoplaced (OptionalFlag | None) – Whether fields are autoplaced (optional)

  • effects (Effects | None) – Text effects (optional)

  • uuid (Uuid) – Unique identifier

__init__(text='', at=<factory>, fields_autoplaced=<factory>, effects=None, uuid=<factory>)
class LabelShape(*values)[source]

Bases: Enum

Label and pin shapes for global labels, hierarchical labels, and sheet pins.

BIDIRECTIONAL = 'bidirectional'
INPUT = 'input'
OUTPUT = 'output'
PASSIVE = 'passive'
TRI_STATE = 'tri_state'
class LibSymbols(symbols=<factory>)[source]

Bases: KiCadObject

Library symbols container token.

The ‘lib_symbols’ token defines a symbol library containing all symbols used in the schematic in the format:

(lib_symbols
    SYMBOL_DEFINITIONS...
)
Parameters:

symbols (List[Symbol]) – List of symbols

__init__(symbols=<factory>)
class Line(start=<factory>, end=<factory>, uuid=None)[source]

Bases: KiCadObject

Line definition token.

The ‘line’ token defines a basic line geometry in the format:

(line (start X Y) (end X Y) (uuid UUID))
Parameters:
  • start (Start) – Start point of the line

  • end (End) – End point of the line

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, uuid=None)
class NetclassFlag(name='', length=None, shape=None, at=None, fields_autoplaced=<factory>, effects=None, uuid=None, properties=<factory>)[source]

Bases: KiCadObject

Netclass flag definition token.

The ‘netclass_flag’ token defines netclass flags in schematics.

Parameters:
  • name (str) – Netclass name

  • length (float | None) – Flag length (optional)

  • shape (str | None) – Flag shape (optional)

  • at (At | None) – Position (optional)

  • fields_autoplaced (OptionalFlag | None) – Whether fields are auto-placed (optional)

  • effects (Effects | None) – Text effects (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • properties (List[Property] | None) – Properties of the netclass flag (optional)

__init__(name='', length=None, shape=None, at=None, fields_autoplaced=<factory>, effects=None, uuid=None, properties=<factory>)
class NoConnect(at=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

No connect definition token.

The ‘no_connect’ token defines a no-connect symbol in the format:

(no_connect
    (at X Y)
    (uuid UUID)
)
Parameters:
  • at (AtXY) – Position

  • uuid (Uuid) – Unique identifier

__init__(at=<factory>, uuid=<factory>)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Paper(size=None, width=None, height=None, portrait=<factory>)[source]

Bases: KiCadObject

Paper settings definition token.

The ‘paper’ token defines paper size and orientation in the format:

(paper PAPER_SIZE | WIDTH HEIGHT [portrait])

Where PAPER_SIZE can be: A0, A1, A2, A3, A4, A5, A, B, C, D, E.

Parameters:
  • size (str | None) – Standard paper size (optional)

  • width (float | None) – Custom paper width (optional)

  • height (float | None) – Custom paper height (optional)

  • portrait (OptionalFlag | None) – Whether paper is in portrait mode (optional)

__init__(size=None, width=None, height=None, portrait=<factory>)
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class Path(value='', reference=<factory>, unit=<factory>, page=<factory>)[source]

Bases: KiCadObject

Path definition token.

The ‘path’ token defines a hierarchical path in the format::
(path “PATH”

(reference “REF”) (unit NUMBER)

)

Parameters:
  • value (str) – Path value

  • reference (KiCadStr | None) – Component reference (optional)

  • unit (KiCadInt | None) – Unit number (optional)

  • page (KiCadStr | None) – Page number (optional)

__init__(value='', reference=<factory>, unit=<factory>, page=<factory>)
class PinRef(number='', uuid=None)[source]

Bases: KiCadObject

Pin reference definition token for schematic symbols.

The ‘pin’ token in schematic symbols references a pin by number in the format::
(pin “NUMBER”

(uuid UUID)

)

Parameters:
  • number (str) – Pin number

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(number='', uuid=None)
class Polygon(pts=<factory>, uuid=None)[source]

Bases: KiCadObject

Polygon definition token.

The ‘polygon’ token defines a polygon with multiple points in the format:

(polygon (pts (xy X Y) (xy X Y) ...) (uuid UUID))
Parameters:
  • pts (Pts) – Polygon vertex points

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, uuid=None)
class Polyline(pts=<factory>, stroke=None, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Polyline definition token.

The ‘polyline’ token defines a connected series of line segments in the format:

(polyline
    (pts (xy X Y) (xy X Y) ...)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • pts (Pts) – Polyline connection points

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=<factory>, uuid=None)
class Project(name='', path=None)[source]

Bases: KiCadObject

Project definition token.

The ‘project’ token defines a project instance in the format::
(project “PROJECT_NAME”
(path “PATH”

(reference “REF”) (unit NUMBER)

)

)

Parameters:
  • name (str) – Project name

  • path (Path | None) – Hierarchical path (optional)

__init__(name='', path=None)
class Property(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)[source]

Bases: KiCadObject

Property definition token.

The ‘property’ token defines properties in two formats:

General properties::

(property “KEY” “VALUE”)

Symbol properties::
(property

“KEY” “VALUE” (id N) POSITION_IDENTIFIER TEXT_EFFECTS

)

Parameters:
  • key (str) – Property key name (must be unique)

  • value (str) – Property value

  • id (KiCadStr | None) – Property ID (optional)

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • unlocked (OptionalFlag | None) – Whether property is unlocked (optional)

  • layer (Layer | None) – Layer assignment (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • hide (OptionalFlag | None) – Hide property flag (optional)

__init__(key='', value='', id=<factory>, at=None, effects=None, unlocked=<factory>, layer=None, uuid=None, hide=<factory>)
class Pts(points=<factory>)[source]

Bases: KiCadObject

Coordinate point list definition token.

The ‘pts’ token defines a list of coordinate points in the format: (pts

(xy X Y) … (xy X Y)

)

Where each xy token defines a single X and Y coordinate pair. The number of points is determined by the object type.

Parameters:

points (List[Xy]) – List of 2D coordinate points

__init__(points=<factory>)
class Rectangle(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Rectangle definition token (symbol form).

The ‘rectangle’ token defines a graphical rectangle in a symbol definition in the format:

(rectangle
    (start X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • start (Start) – Start point of the rectangle

  • end (End) – End point of the rectangle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class RowHeights(heights=<factory>)[source]

Bases: KiCadObject

Row heights definition token.

The ‘row_heights’ token defines row height values in the format::

(row_heights HEIGHT1 HEIGHT2 …)

Parameters:

heights (List[float]) – List of row height values

__init__(heights=<factory>)
class RuleArea(polylines=<factory>)[source]

Bases: KiCadObject

Rule area definition token.

The ‘rule_area’ token defines rule areas in schematics.

Parameters:

polylines (List[Polyline] | None) – Polylines defining area (optional)

__init__(polylines=<factory>)
class SchematicSymbol(lib_name=None, lib_id=<factory>, at=None, mirror=<factory>, unit=<factory>, exclude_from_sim=None, in_bom=None, on_board=None, dnp=None, fields_autoplaced=None, uuid=None, properties=<factory>, pins=<factory>, text=<factory>, instances=None)[source]

Bases: KiCadObject

Schematic symbol instance definition token.

References a symbol definition via lib_id and adds instance-specific properties.

The ‘symbol’ token in schematics defines symbol instances in the format::
(symbol

(lib_id “LIBRARY:SYMBOL”) (at X Y ANGLE) (unit NUMBER) (exclude_from_sim BOOLEAN) (in_bom BOOLEAN) (on_board BOOLEAN) (dnp BOOLEAN) (fields_autoplaced BOOLEAN) (uuid UUID) PROPERTIES… PINS… (instances …)

)

Parameters:
  • lib_name (str | None) – Library name (optional)

  • lib_id (KiCadStr | None) – Library identifier referencing symbol definition (optional)

  • at (At | None) – Position and rotation (optional)

  • mirror (KiCadStr | None) – Mirror transformation (optional)

  • unit (KiCadInt | None) – Unit number (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether to exclude from simulation (optional)

  • in_bom (OptionalFlag | None) – Whether to include in BOM (optional)

  • on_board (OptionalFlag | None) – Whether to place on board (optional)

  • dnp (OptionalFlag | None) – Do not populate flag (optional)

  • fields_autoplaced (OptionalFlag | None) – Whether fields are auto-placed (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • properties (List[Property] | None) – List of properties (optional)

  • pins (List[PinRef] | None) – List of pin references (optional)

  • text (List[Text] | None) – List of text elements (optional)

  • instances (SymbolInstances | None) – Symbol instances (optional)

__init__(lib_name=None, lib_id=<factory>, at=None, mirror=<factory>, unit=<factory>, exclude_from_sim=None, in_bom=None, on_board=None, dnp=None, fields_autoplaced=None, uuid=None, properties=<factory>, pins=<factory>, text=<factory>, instances=None)
class Sheet(at=<factory>, size=<factory>, fields_autoplaced=<factory>, stroke=None, fill=None, uuid=<factory>, properties=<factory>, pins=<factory>, exclude_from_sim=<factory>, in_bom=<factory>, on_board=<factory>, dnp=<factory>, rectangles=<factory>, instances=None)[source]

Bases: KiCadObject

Hierarchical sheet definition token.

The ‘sheet’ token defines a hierarchical sheet in the format:

(sheet
    (at X Y)
    (size WIDTH HEIGHT)
    (fields_autoplaced)
    (stroke STROKE_DEFINITION)
    (fill FILL)
    (uuid UUID)
    (property "Sheetname" "NAME")
    (property "Sheetfile" "FILE")
    (pin "NAME" SHAPE (at X Y ANGLE) (effects EFFECTS) (uuid UUID))
    ...
)
Parameters:
  • at (AtXY) – Position

  • size (Size) – Sheet size

  • fields_autoplaced (OptionalFlag | None) – Whether fields are autoplaced (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • fill (Fill | None) – Fill definition (optional)

  • uuid (Uuid) – Unique identifier

  • properties (List[Property]) – List of properties

  • pins (List[SheetPin] | None) – List of sheet pins (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether sheet is excluded from simulation (optional)

  • in_bom (OptionalFlag | None) – Whether sheet appears in BOM (optional)

  • on_board (OptionalFlag | None) – Whether sheet is exported to PCB (optional)

  • dnp (OptionalFlag | None) – Do not populate flag (optional)

  • rectangles (List[Rectangle] | None) – List of rectangle graphical items (optional)

  • instances (SheetLocalInstances | None) – Sheet local instances (optional)

__init__(at=<factory>, size=<factory>, fields_autoplaced=<factory>, stroke=None, fill=None, uuid=<factory>, properties=<factory>, pins=<factory>, exclude_from_sim=<factory>, in_bom=<factory>, on_board=<factory>, dnp=<factory>, rectangles=<factory>, instances=None)
class SheetInstance(path='', page=<factory>)[source]

Bases: KiCadObject

Sheet instance definition token.

The ‘path’ token defines a sheet instance in the format:

(path "PATH_STRING"
    (page "PAGE_NUMBER")
)
Parameters:
  • path (str) – Hierarchical path string

  • page (KiCadStr) – Page object

__init__(path='', page=<factory>)
class SheetInstances(sheet_instances=<factory>)[source]

Bases: KiCadObject

Sheet instances container definition token.

The ‘sheet_instances’ token defines sheet instances in the format:

(sheet_instances
    (path "PATH1" (page "PAGE1"))
    (path "PATH2" (page "PAGE2"))
    ...
)
Parameters:

sheet_instances (List[SheetInstance]) – List of sheet instances

__init__(sheet_instances=<factory>)
class SheetLocalInstances(project=<factory>)[source]

Bases: KiCadObject

Sheet local instances definition token.

The ‘instances’ token defines local sheet instances in the format:

(instances
    (project "PROJECT_NAME"
        (path "/PATH" (page "PAGE"))
    )
)
Parameters:

project (List[Project]) – List of project data

__init__(project=<factory>)
class SheetPin(name='', shape=LabelShape.INPUT, at=<factory>, effects=None, uuid=<factory>)[source]

Bases: KiCadObject

Sheet pin definition token.

The ‘pin’ token defines a hierarchical sheet pin in the format:

(pin "NAME" SHAPE (at X Y ANGLE) (effects EFFECTS) (uuid UUID))
Parameters:
  • name (str) – Pin name string

  • shape (LabelShape) – Pin shape/direction

  • at (At) – Position and angle

  • effects (Effects | None) – Text effects (optional)

  • uuid (Uuid) – Unique identifier

__init__(name='', shape=LabelShape.INPUT, at=<factory>, effects=None, uuid=<factory>)
class Size(width=0.0, height=0.0)[source]

Bases: KiCadObject

Size definition token.

The ‘size’ token defines width and height dimensions in the format: (size WIDTH HEIGHT)

Parameters:
  • width (float) – Width dimension

  • height (float) – Height dimension

__init__(width=0.0, height=0.0)
class Stroke(width=<factory>, type=<factory>, color=None)[source]

Bases: KiCadObject

Stroke definition token.

The ‘stroke’ token defines how the outlines of graphical objects are drawn in the format: (stroke

(width WIDTH) (type TYPE) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • width (KiCadFloat) – Line width specification

  • type (Type) – Stroke line style specification

  • color (Color | None) – Line color specification (optional)

__init__(width=<factory>, type=<factory>, color=None)
class SymbolInstances(projects=<factory>)[source]

Bases: KiCadObject

Symbol instances definition token.

The ‘instances’ token defines symbol instance data in the format::
(instances
(project “PROJECT_NAME”
(path “PATH”

(reference “REF”) (unit NUMBER)

)

)

)

Parameters:

projects (List[Project]) – List of project instances

__init__(projects=<factory>)
class Table(column_count=None, border=None, separators=None, column_widths=None, row_heights=None, cells=None)[source]

Bases: KiCadObject

Table definition token for schematics.

The ‘table’ token defines tables in schematics. This is a basic implementation for parsing support.

Parameters:
  • column_count (int | None) – Number of columns (optional)

  • border (TableBorder | None) – Border configuration (optional)

  • separators (TableSeparators | None) – Separator configuration (optional)

  • column_widths (ColumnWidths | None) – Column width values (optional)

  • row_heights (RowHeights | None) – Row height values (optional)

  • cells (Cells | None) – Table cells (optional)

__init__(column_count=None, border=None, separators=None, column_widths=None, row_heights=None, cells=None)
class TableBorder(external=None, header=None, stroke=None)[source]

Bases: KiCadObject

Table border definition token.

The ‘border’ token defines border configuration for tables in the format::

(border (external yes) (header yes) (stroke (width WIDTH) (type TYPE)))

Parameters:
  • external (OptionalFlag | None) – Whether external border is shown (optional)

  • header (OptionalFlag | None) – Whether header border is shown (optional)

  • stroke (Stroke | None) – Stroke definition for border lines (optional)

__init__(external=None, header=None, stroke=None)
class TableCell(text='', exclude_from_sim=None, at=None, size=None, margins=None, span=None, fill=None, effects=None, uuid=None)[source]

Bases: KiCadObject

Table cell definition token.

The ‘table_cell’ token defines individual table cells in the format::
(table_cell “TEXT”

(exclude_from_sim BOOLEAN) (at X Y ANGLE) (size WIDTH HEIGHT) (margins LEFT TOP RIGHT BOTTOM) (span COLS ROWS) (fill FILL_DEF) (effects EFFECTS_DEF) (uuid UUID)

)

Parameters:
  • text (str) – Cell text content

  • exclude_from_sim (OptionalFlag | None) – Whether to exclude from simulation (optional)

  • at (At | None) – Position and rotation (optional)

  • size (Size | None) – Cell size (optional)

  • margins (TableMargins | None) – Cell margins (optional)

  • span (TableSpan | None) – Cell span (optional)

  • fill (Fill | None) – Fill definition (optional)

  • effects (Effects | None) – Text effects (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(text='', exclude_from_sim=None, at=None, size=None, margins=None, span=None, fill=None, effects=None, uuid=None)
class TableMargins(left=0.0, top=0.0, right=0.0, bottom=0.0)[source]

Bases: KiCadObject

Table margins definition token.

The ‘margins’ token defines cell margins in the format::

(margins LEFT TOP RIGHT BOTTOM)

Parameters:
  • left (float) – Left margin

  • top (float) – Top margin

  • right (float) – Right margin

  • bottom (float) – Bottom margin

__init__(left=0.0, top=0.0, right=0.0, bottom=0.0)
class TableSeparators(rows=None, cols=None, stroke=None)[source]

Bases: KiCadObject

Table separators definition token.

The ‘separators’ token defines separator configuration for tables in the format::

(separators (rows yes) (cols yes) (stroke (width WIDTH) (type TYPE)))

Parameters:
  • rows (OptionalFlag | None) – Whether row separators are shown (optional)

  • cols (OptionalFlag | None) – Whether column separators are shown (optional)

  • stroke (Stroke | None) – Stroke definition for separator lines (optional)

__init__(rows=None, cols=None, stroke=None)
class TableSpan(cols=1, rows=1)[source]

Bases: KiCadObject

Table span definition token.

The ‘span’ token defines cell span in the format::

(span COLS ROWS)

Parameters:
  • cols (int) – Number of columns to span

  • rows (int) – Number of rows to span

__init__(cols=1, rows=1)
class Text(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)[source]

Bases: KiCadObject

Text content definition token.

The ‘text’ token defines text content in the format: (text “TEXT_CONTENT”

(at X Y [ANGLE]) (effects EFFECTS)

)

Parameters:
  • content (str) – Text content

  • at (At | None) – Position and rotation (optional)

  • effects (Effects | None) – Text effects (optional)

  • exclude_from_sim (OptionalFlag | None) – Whether to exclude from simulation (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(content='', at=None, effects=None, exclude_from_sim=<factory>, uuid=None)
class TitleBlock(title=<factory>, date=<factory>, rev=<factory>, company=<factory>, comments=<factory>)[source]

Bases: KiCadObject

Title block definition token.

The ‘title_block’ token defines the document title block in the format:

(title_block
    (title "TITLE")
    (date "DATE")
    (rev "REVISION")
    (company "COMPANY_NAME")
    (comment N "COMMENT")
)
Parameters:
  • title (KiCadStr | None) – Document title (optional)

  • date (KiCadStr | None) – Document date (optional)

  • rev (KiCadStr | None) – Document revision (optional)

  • company (KiCadStr | None) – Company name (optional)

  • comments (List[Comment] | None) – List of comments (optional)

__init__(title=<factory>, date=<factory>, rev=<factory>, company=<factory>, comments=<factory>)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class Wire(pts=<factory>, stroke=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Wire definition token.

The ‘wire’ token defines wires in the schematic in the format:

(wire
    COORDINATE_POINT_LIST
    STROKE_DEFINITION
    UNIQUE_IDENTIFIER
)
Parameters:
  • pts (Pts) – Wire connection points

  • stroke (Stroke) – Stroke definition

  • uuid (Uuid) – Unique identifier

__init__(pts=<factory>, stroke=<factory>, uuid=<factory>)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.project_settings module

Project settings elements for KiCad JSON project files - .kicad_pro format.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class BoardDefaults(apply_defaults_to_fp_fields=None, apply_defaults_to_fp_shapes=None, apply_defaults_to_fp_text=None, board_outline_line_width=None, copper_line_width=None, copper_text_italic=None, copper_text_size_h=None, copper_text_size_v=None, copper_text_thickness=None, copper_text_upright=None, courtyard_line_width=None, dimension_precision=None, dimension_units=None, dimensions=None, fab_line_width=None, fab_text_italic=None, fab_text_size_h=None, fab_text_size_v=None, fab_text_thickness=None, fab_text_upright=None, other_line_width=None, other_text_italic=None, other_text_size_h=None, other_text_size_v=None, other_text_thickness=None, other_text_upright=None, pads=None, silk_line_width=None, silk_text_italic=None, silk_text_size_h=None, silk_text_size_v=None, silk_text_thickness=None, silk_text_upright=None, zones=None)[source]

Bases: JsonObject

Board design defaults settings.

In the standard KiCad.kicad_pro file, this is an empty object {}, so all fields are optional and represent extended configurations.

__init__(apply_defaults_to_fp_fields=None, apply_defaults_to_fp_shapes=None, apply_defaults_to_fp_text=None, board_outline_line_width=None, copper_line_width=None, copper_text_italic=None, copper_text_size_h=None, copper_text_size_v=None, copper_text_thickness=None, copper_text_upright=None, courtyard_line_width=None, dimension_precision=None, dimension_units=None, dimensions=None, fab_line_width=None, fab_text_italic=None, fab_text_size_h=None, fab_text_size_v=None, fab_text_thickness=None, fab_text_upright=None, other_line_width=None, other_text_italic=None, other_text_size_h=None, other_text_size_v=None, other_text_thickness=None, other_text_upright=None, pads=None, silk_line_width=None, silk_text_italic=None, silk_text_size_h=None, silk_text_size_v=None, silk_text_thickness=None, silk_text_upright=None, zones=None)
class BoardSettings(design_settings=<factory>, ipc2581=<factory>, layer_pairs=<factory>, layer_presets=<factory>, viewports=<factory>, threeD_viewports=<factory>)[source]

Bases: JsonObject

Board-specific settings.

Based on standard KiCad.kicad_pro structure.

__init__(design_settings=<factory>, ipc2581=<factory>, layer_pairs=<factory>, layer_presets=<factory>, viewports=<factory>, threeD_viewports=<factory>)
class CvpcbSettings(equivalence_files=<factory>)[source]

Bases: JsonObject

Component-Footprint assignment tool settings.

__init__(equivalence_files=<factory>)
class DesignSettings(defaults=<factory>, diff_pair_dimensions=<factory>, drc_exclusions=<factory>, rules=<factory>, track_widths=<factory>, via_dimensions=<factory>, meta=None, rule_severities=None, teardrop_options=None, teardrop_parameters=None, tuning_pattern_settings=None, zones_allow_external_fillets=None, zones_use_no_outline=None)[source]

Bases: JsonObject

Board design settings.

Based on standard KiCad.kicad_pro structure.

__init__(defaults=<factory>, diff_pair_dimensions=<factory>, drc_exclusions=<factory>, rules=<factory>, track_widths=<factory>, via_dimensions=<factory>, meta=None, rule_severities=None, teardrop_options=None, teardrop_parameters=None, tuning_pattern_settings=None, zones_allow_external_fillets=None, zones_use_no_outline=None)
class ERCSettings(erc_exclusions=None, meta=None, pin_map=None, rule_severities=None)[source]

Bases: JsonObject

ERC (Electrical Rules Check) settings.

Not present in standard KiCad.kicad_pro, so all fields are optional.

__init__(erc_exclusions=None, meta=None, pin_map=None, rule_severities=None)
class IPC2581Settings(dist='', distpn='', internal_id='', mfg='', mpn='')[source]

Bases: JsonObject

IPC2581 export settings.

__init__(dist='', distpn='', internal_id='', mfg='', mpn='')
class JsonObject[source]

Bases: ABC

Base class for JSON-based KiCad objects.

This class provides similar functionality to KiCadObject but for JSON format files like .kicad_pro project files. It automatically handles serialization/deserialization based on dataclass field definitions.

Features: - Automatic JSON parsing based on dataclass field definitions - Round-trip preservation with preserve_original option - Type-aware serialization/deserialization for nested objects - File I/O methods with extension validation and encoding support - Recursive handling of Optional, List, and nested JsonObject types

Usage:

@dataclass class MyKiCadFile(JsonObject):

version: int = 1 data: Optional[Dict[str, Any]] = None

# Parse from file obj = MyKiCadFile.from_file(“file.json”)

# Parse from dictionary obj = MyKiCadFile.from_dict({“version”: 2, “data”: {…}})

# Export with exact round-trip preservation data = obj.to_dict(preserve_original=True)

__init__()
classmethod from_dict(data)[source]

Create instance from dictionary data.

Parameters:

data (Dict[str, Any]) – Dictionary containing the data

Returns:

Instance of the class

Return type:

T

classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from JSON file.

Parameters:
  • file_path (str) – Path to JSON file

  • strictness (ParseStrictness) – Parse strictness level (not used for JSON, kept for compatibility)

  • encoding (str) – File encoding (default: utf-8)

Returns:

Instance of the class

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

  • ValueError – If the file contains invalid JSON

  • UnicodeDecodeError – If the file encoding is incorrect

Return type:

T

classmethod from_str(json_string, strictness=ParseStrictness.STRICT)[source]

Parse from JSON string.

Parameters:
  • json_string (str) – JSON content as string

  • strictness (ParseStrictness) – Parse strictness level (not used for JSON, kept for compatibility)

Returns:

Instance of the class

Raises:

ValueError – If the JSON string is invalid

Return type:

T

save_to_file(file_path, encoding='utf-8', preserve_original=False)[source]

Save to JSON file format.

Parameters:
  • file_path (str) – Path to write the JSON file

  • encoding (str) – File encoding (default: utf-8)

  • preserve_original (bool) – Whether to preserve original structure

to_dict(preserve_original=False)[source]

Convert to dictionary format.

Parameters:

preserve_original (bool) – If True and original data exists, return updated original data preserving the exact structure

Returns:

Dictionary representation

Return type:

Dict[str, Any]

to_json_str(pretty_print=True, preserve_original=False)[source]

Convert to JSON string format.

Parameters:
  • pretty_print (bool) – Whether to format JSON with indentation

  • preserve_original (bool) – If True, preserve original structure for exact round-trip

Returns:

JSON string representation

Return type:

str

class KicadProject(board=<factory>, boards=<factory>, cvpcb=<factory>, libraries=<factory>, meta=<factory>, net_settings=<factory>, pcbnew=<factory>, schematic=<factory>, sheets=<factory>, text_variables=<factory>, erc=None)[source]

Bases: JsonObject

KiCad project file definition (.kicad_pro format).

The .kicad_pro file is a JSON format file that contains project configuration and settings for KiCad projects.

Based on the standard KiCad.kicad_pro structure with all standard fields and optional extended fields for more complex projects.

Parameters:
  • board (BoardSettings) – Board-specific settings

  • boards (List[str]) – List of board files in project

  • cvpcb (CvpcbSettings) – Component-Footprint assignment settings

  • libraries (LibrarySettings) – Library configuration

  • meta (ProjectMeta) – Project metadata

  • net_settings (NetSettings) – Network classes and settings

  • pcbnew (PcbnewSettings) – PCB editor settings

  • schematic (SchematicSettings) – Schematic-specific settings

  • sheets (List[Dict[str, Any]]) – List of schematic sheets

  • text_variables (Dict[str, str]) – Project text variables

  • erc (ERCSettings | None) – ERC settings (optional, not in standard file)

  • _original_data – Internal storage of original input data for exact round-trip

__init__(board=<factory>, boards=<factory>, cvpcb=<factory>, libraries=<factory>, meta=<factory>, net_settings=<factory>, pcbnew=<factory>, schematic=<factory>, sheets=<factory>, text_variables=<factory>, erc=None)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from JSON file - convenience method for project operations.

Parameters:
  • file_path (str) – Path to .kicad_pro file

  • strictness (ParseStrictness) – Parse strictness level (not used for JSON)

  • encoding (str) – File encoding (default: utf-8)

Returns:

KicadProject instance

Return type:

KicadProject

save_to_file(file_path, encoding='utf-8', preserve_original=False)[source]

Save to .kicad_pro file format.

Parameters:
  • file_path (str) – Path to write the .kicad_pro file

  • encoding (str) – File encoding (default: utf-8)

  • preserve_original (bool) – Whether to preserve original structure

class LibrarySettings(pinned_footprint_libs=<factory>, pinned_symbol_libs=<factory>)[source]

Bases: JsonObject

Library settings configuration.

__init__(pinned_footprint_libs=<factory>, pinned_symbol_libs=<factory>)
class NetClass(name='Default', bus_width=12.0, clearance=0.2, diff_pair_gap=0.25, diff_pair_via_gap=0.25, diff_pair_width=0.2, line_style=0, microvia_diameter=0.3, microvia_drill=0.1, pcb_color='rgba(0, 0, 0, 0.000)', priority=2147483647, schematic_color='rgba(0, 0, 0, 0.000)', track_width=0.2, via_diameter=0.6, via_drill=0.3, wire_width=6.0)[source]

Bases: JsonObject

Network class definition.

Values from standard KiCad.kicad_pro file.

__init__(name='Default', bus_width=12.0, clearance=0.2, diff_pair_gap=0.25, diff_pair_via_gap=0.25, diff_pair_width=0.2, line_style=0, microvia_diameter=0.3, microvia_drill=0.1, pcb_color='rgba(0, 0, 0, 0.000)', priority=2147483647, schematic_color='rgba(0, 0, 0, 0.000)', track_width=0.2, via_diameter=0.6, via_drill=0.3, wire_width=6.0)
class NetSettings(classes=<factory>, meta=<factory>, net_colors=None, netclass_assignments=None, netclass_patterns=<factory>)[source]

Bases: JsonObject

Network settings configuration.

Based on standard KiCad.kicad_pro structure.

__init__(classes=<factory>, meta=<factory>, net_colors=None, netclass_assignments=None, netclass_patterns=<factory>)
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class PcbnewSettings(last_paths=<factory>, page_layout_descr_file='')[source]

Bases: JsonObject

PCB editor specific settings.

Based on standard KiCad.kicad_pro structure.

__init__(last_paths=<factory>, page_layout_descr_file='')
class ProjectMeta(filename='KiCad.kicad_pro', version=3)[source]

Bases: JsonObject

Project metadata.

Based on standard KiCad.kicad_pro values.

__init__(filename='KiCad.kicad_pro', version=3)
class SchematicBOMSettings(annotate_start_num=None, bom_export_filename=None, bom_fmt_presets=None, bom_fmt_settings=None, bom_presets=None, bom_settings=None, connection_grid_size=None, drawing=None, net_format_name=None, ngspice=None, page_layout_descr_file=None, plot_directory=None, space_save_all_events=None, spice_adjust_passive_values=None, spice_current_sheet_as_root=None, spice_external_command=None, spice_model_current_sheet_as_root=None, spice_save_all_currents=None, spice_save_all_dissipations=None, spice_save_all_voltages=None, subpart_first_id=None, subpart_id_separator=None)[source]

Bases: JsonObject

BOM (Bill of Materials) settings.

Not present in standard KiCad.kicad_pro, so all fields are optional.

__init__(annotate_start_num=None, bom_export_filename=None, bom_fmt_presets=None, bom_fmt_settings=None, bom_presets=None, bom_settings=None, connection_grid_size=None, drawing=None, net_format_name=None, ngspice=None, page_layout_descr_file=None, plot_directory=None, space_save_all_events=None, spice_adjust_passive_values=None, spice_current_sheet_as_root=None, spice_external_command=None, spice_model_current_sheet_as_root=None, spice_save_all_currents=None, spice_save_all_dissipations=None, spice_save_all_voltages=None, subpart_first_id=None, subpart_id_separator=None)
class SchematicSettings(legacy_lib_dir='', legacy_lib_list=<factory>, meta=None)[source]

Bases: JsonObject

Schematic-specific settings.

Based on standard KiCad.kicad_pro structure.

__init__(legacy_lib_dir='', legacy_lib_list=<factory>, meta=None)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

Graphics and Drawing

kicadfiles.primitive_graphics module

Primitive graphics elements for KiCad S-expressions - basic geometric shapes.

class Arc(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Arc definition token.

The ‘arc’ token defines a graphical arc in a symbol definition in the format:

(arc
    (start X Y)
    (mid X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
    (uuid UUID)
)
Parameters:
  • start (Start) – Start point of the arc

  • mid (Mid | None) – Mid point of the arc (optional)

  • end (End) – End point of the arc

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, mid=None, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class Bezier(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)[source]

Bases: KiCadObject

Bezier curve definition token.

The ‘bezier’ token defines a graphic Cubic Bezier curve in the format:

(bezier
    COORDINATE_POINT_LIST
    (layer LAYER_DEFINITION)
    (width WIDTH)
    (uuid UUID)
)
Parameters:
  • pts (Pts) – List of X/Y coordinates of the four points of the curve

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (Fill | None) – Fill definition for filling (optional)

  • width (KiCadFloat | None) – Line width of the curve (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=None, width=<factory>, uuid=None)
class Center(x=0.0, y=0.0)[source]

Bases: KiCadObject

Center point definition token.

The ‘center’ token defines a center point in the format:

(center X Y)
Parameters:
  • x (float) – Horizontal position of the center point

  • y (float) – Vertical position of the center point

__init__(x=0.0, y=0.0)
class Circle(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Circle definition token.

The ‘circle’ token defines a graphical circle in a symbol definition in the format:

(circle
    (center X Y)
    (radius RADIUS)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • center (Center) – Center point of the circle

  • radius (KiCadFloat) – Radius length of the circle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(center=<factory>, radius=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class End(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

End point definition token.

The ‘end’ token defines an end point in the format:

(end X Y)
Parameters:
  • x (float) – Horizontal position of the end point

  • y (float) – Vertical position of the end point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Fill(type=None, color=None)[source]

Bases: KiCadObject

Fill definition token.

The ‘fill’ token defines how schematic and symbol library graphical items are filled in the format: (fill

(type none | outline | background) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • type (Type | None) – Fill type specification (optional)

  • color (Color | None) – Fill color specification (optional)

__init__(type=None, color=None)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class Line(start=<factory>, end=<factory>, uuid=None)[source]

Bases: KiCadObject

Line definition token.

The ‘line’ token defines a basic line geometry in the format:

(line (start X Y) (end X Y) (uuid UUID))
Parameters:
  • start (Start) – Start point of the line

  • end (End) – End point of the line

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, uuid=None)
class Mid(x=0.0, y=0.0)[source]

Bases: KiCadObject

Mid point definition token.

The ‘mid’ token defines a mid point in the format:

(mid X Y)
Parameters:
  • x (float) – Horizontal position of the mid point

  • y (float) – Vertical position of the mid point

__init__(x=0.0, y=0.0)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Polygon(pts=<factory>, uuid=None)[source]

Bases: KiCadObject

Polygon definition token.

The ‘polygon’ token defines a polygon with multiple points in the format:

(polygon (pts (xy X Y) (xy X Y) ...) (uuid UUID))
Parameters:
  • pts (Pts) – Polygon vertex points

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, uuid=None)
class Polyline(pts=<factory>, stroke=None, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Polyline definition token.

The ‘polyline’ token defines a connected series of line segments in the format:

(polyline
    (pts (xy X Y) (xy X Y) ...)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • pts (Pts) – Polyline connection points

  • stroke (Stroke | None) – Stroke definition for outline (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, stroke=None, fill=<factory>, uuid=None)
class Pts(points=<factory>)[source]

Bases: KiCadObject

Coordinate point list definition token.

The ‘pts’ token defines a list of coordinate points in the format: (pts

(xy X Y) … (xy X Y)

)

Where each xy token defines a single X and Y coordinate pair. The number of points is determined by the object type.

Parameters:

points (List[Xy]) – List of 2D coordinate points

__init__(points=<factory>)
class Rect(start=<factory>, end=<factory>)[source]

Bases: KiCadObject

Rectangle definition token.

The ‘rect’ token defines a basic rectangle geometry in the format:

(rect (start X Y) (end X Y))
Parameters:
  • start (Start) – Start corner of the rectangle

  • end (End) – End corner of the rectangle

__init__(start=<factory>, end=<factory>)
class Rectangle(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)[source]

Bases: KiCadObject

Rectangle definition token (symbol form).

The ‘rectangle’ token defines a graphical rectangle in a symbol definition in the format:

(rectangle
    (start X Y)
    (end X Y)
    STROKE_DEFINITION
    FILL_DEFINITION
)
Parameters:
  • start (Start) – Start point of the rectangle

  • end (End) – End point of the rectangle

  • stroke (Stroke) – Stroke definition for outline

  • fill (Fill) – Fill definition for filling

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, end=<factory>, stroke=<factory>, fill=<factory>, uuid=None)
class Start(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Start point definition token.

The ‘start’ token defines a start point in the format: (start X Y)

Parameters:
  • x (float) – Horizontal position of the start point

  • y (float) – Vertical position of the start point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Stroke(width=<factory>, type=<factory>, color=None)[source]

Bases: KiCadObject

Stroke definition token.

The ‘stroke’ token defines how the outlines of graphical objects are drawn in the format: (stroke

(width WIDTH) (type TYPE) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • width (KiCadFloat) – Line width specification

  • type (Type) – Stroke line style specification

  • color (Color | None) – Line color specification (optional)

__init__(width=<factory>, type=<factory>, color=None)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.advanced_graphics module

Advanced graphics elements for KiCad S-expressions - complex graphical objects.

class At(x=0.0, y=0.0, angle=0.0)[source]

Bases: KiCadObject

Position identifier token that defines positional coordinates and rotation of an object.

The ‘at’ token defines the positional coordinates in the format:

(at X Y [ANGLE])

Note

Symbol text ANGLEs are stored in tenth’s of a degree. All other ANGLEs are stored in degrees. For 3D model positioning, use ModelAt class which supports (at (xyz X Y Z)) format.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

  • angle (float | None) – Rotational angle of the object

__init__(x=0.0, y=0.0, angle=0.0)
class Center(x=0.0, y=0.0)[source]

Bases: KiCadObject

Center point definition token.

The ‘center’ token defines a center point in the format:

(center X Y)
Parameters:
  • x (float) – Horizontal position of the center point

  • y (float) – Vertical position of the center point

__init__(x=0.0, y=0.0)
class Dimension(locked=<factory>, type=<factory>, layer=<factory>, uuid=<factory>, pts=<factory>, height=<factory>, orientation=<factory>, leader_length=<factory>, gr_text=None, format=None, style=<factory>)[source]

Bases: KiCadObject

Dimension definition token.

The ‘dimension’ token defines measurement dimensions in the format:

(dimension
    [locked]
    (type DIMENSION_TYPE)
    (layer LAYER_DEFINITION)
    (uuid UUID)
    (pts (xy X Y) (xy X Y))
    [(height HEIGHT)]
    [(orientation ORIENTATION)]
    [(leader_length LEADER_LENGTH)]
    [(gr_text GRAPHICAL_TEXT)]
    [(format DIMENSION_FORMAT)]
    (style DIMENSION_STYLE)
)
Parameters:
  • locked (OptionalFlag | None) – Whether dimension is locked (optional)

  • type (Type) – Dimension type (aligned | leader | center | orthogonal | radial)

  • layer (Layer) – Layer definition

  • uuid (Uuid) – Unique identifier

  • pts (Pts) – Dimension points

  • height (KiCadFloat | None) – Height for aligned dimensions (optional)

  • orientation (KiCadFloat | None) – Orientation angle for orthogonal dimensions (optional)

  • leader_length (KiCadFloat | None) – Leader length for radial dimensions (optional)

  • gr_text (GrText | None) – Dimension text (optional)

  • format (Format | None) – Dimension format (optional)

  • style (KiCadStr) – Dimension style

__init__(locked=<factory>, type=<factory>, layer=<factory>, uuid=<factory>, pts=<factory>, height=<factory>, orientation=<factory>, leader_length=<factory>, gr_text=None, format=None, style=<factory>)
class Effects(font=None, justify=None, hide=<factory>, href=<factory>)[source]

Bases: KiCadObject

Text effects definition token.

The ‘effects’ token defines text formatting effects in the format:

(effects
    (font [size SIZE] [thickness THICKNESS] [bold] [italic])
    [(justify JUSTIFY)]
    [hide]
)
Parameters:
  • font (Font | None) – Font definition (optional)

  • justify (Justify | None) – Text justification (optional)

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • href (KiCadStr | None) – Hyperlink reference (optional)

__init__(font=None, justify=None, hide=<factory>, href=<factory>)
class End(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

End point definition token.

The ‘end’ token defines an end point in the format:

(end X Y)
Parameters:
  • x (float) – Horizontal position of the end point

  • y (float) – Vertical position of the end point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Format(prefix=<factory>, suffix=<factory>, units=<factory>, units_format=<factory>, precision=<factory>, override_value=<factory>, suppress_zeros=<factory>)[source]

Bases: KiCadObject

Dimension format definition token.

The ‘format’ token defines formatting for dimension text in the format:

(format
    [(prefix "PREFIX")]
    [(suffix "SUFFIX")]
    (units UNITS)
    (units_format UNITS_FORMAT)
    (precision PRECISION)
    [(override_value "VALUE")]
    [(suppress_zeros yes | no)]
)
Parameters:
  • prefix (KiCadStr | None) – Text prefix (optional)

  • suffix (KiCadStr | None) – Text suffix (optional)

  • units (KiCadStr) – Units type (0=inches, 1=mils, 2=mm, 3=auto)

  • units_format (KiCadInt) – Units format (0=no suffix, 1=bare, 2=parenthesis)

  • precision (KiCadInt) – Precision digits

  • override_value (KiCadStr | None) – Override text value (optional)

  • suppress_zeros (OptionalFlag | None) – Whether to suppress trailing zeros (optional)

__init__(prefix=<factory>, suffix=<factory>, units=<factory>, units_format=<factory>, precision=<factory>, override_value=<factory>, suppress_zeros=<factory>)
class FpArc(start=<factory>, mid=None, end=<factory>, layer=<factory>, width=<factory>, stroke=None, locked=<factory>, angle=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint arc definition token.

The ‘fp_arc’ token defines an arc in a footprint in the format:

(fp_arc
    (start X Y)
    [(mid X Y)]
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    [STROKE_DEFINITION]
    [(locked)]
    [(uuid UUID)]
    [(angle ANGLE)]
)
Parameters:
  • start (Start) – Start point coordinates

  • mid (Pos | None) – Mid point coordinates (optional)

  • end (End) – End point coordinates

  • layer (Layer | None) – Layer definition

  • width (KiCadFloat | None) – Line width (prior to version 7)

  • stroke (Stroke | None) – Stroke definition (from version 7) (optional)

  • locked (OptionalFlag | None) – Whether the arc is locked (optional)

  • angle (KiCadFloat | None) – Arc angle in degrees (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(start=<factory>, mid=None, end=<factory>, layer=<factory>, width=<factory>, stroke=None, locked=<factory>, angle=<factory>, uuid=None)
class FpCircle(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, fill=<factory>, locked=<factory>)[source]

Bases: KiCadObject

Footprint circle definition token.

The ‘fp_circle’ token defines a circle in a footprint in the format:

(fp_circle
    (center X Y)
    (end X Y)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • center (Center) – Center point

  • end (End) – End point

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • locked (OptionalFlag | None) – Whether the circle is locked (optional)

__init__(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, fill=<factory>, locked=<factory>)
class FpCurve(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)[source]

Bases: KiCadObject

Footprint curve definition token.

The ‘fp_curve’ token defines a Bezier curve in a footprint in the format:

(fp_curve
    (pts (xy X Y) (xy X Y) (xy X Y) (xy X Y))
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • pts (Pts) – Control points

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • locked (OptionalFlag | None) – Whether the curve is locked (optional)

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)
class FpLine(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)[source]

Bases: KiCadObject

Footprint line definition token.

The ‘fp_line’ token defines a line in a footprint in the format:

(fp_line
    (start X Y)
    (end X Y)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • start (Start) – Start point

  • end (End) – End point

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • locked (OptionalFlag | None) – Whether the line is locked (optional)

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)
class FpPoly(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint polygon definition token.

The ‘fp_poly’ token defines a polygon in a footprint in the format:

(fp_poly
    (pts (xy X Y) ...)
    (layer LAYER)
    (width WIDTH)
    [(tstamp UUID)]
)
Parameters:
  • pts (Pts) – Polygon points

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (optional)

  • tstamp (KiCadStr | None) – Timestamp UUID (optional)

  • stroke (Stroke | None) – Stroke definition (optional)

  • fill (OptionalFlag | None) – Fill definition (optional)

  • locked (OptionalFlag | None) – Whether thepolygon is locked (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)
class FpRect(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Footprint rectangle definition token.

The ‘fp_rect’ token defines a graphic rectangle in a footprint definition in the format:

(fp_rect
    (start X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    STROKE_DEFINITION
    [(fill yes | no)]
    [(locked)]
    (uuid UUID)
)
Parameters:
  • start (Start) – Coordinates of the upper left corner

  • end (End) – Coordinates of the lower right corner

  • layer (Layer) – Layer definition

  • width (KiCadFloat | None) – Line width (prior to version 7) (optional)

  • stroke (Stroke | None) – Stroke definition (from version 7) (optional)

  • fill (OptionalFlag | None) – Whether the rectangle is filled (yes/no) (optional)

  • locked (OptionalFlag | None) – Whether the rectangle cannot be edited (optional)

  • uuid (Uuid) – Unique identifier

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)
class FpText(type='', text='', at=<factory>, unlocked=<factory>, layer=<factory>, hide=<factory>, effects=<factory>, uuid=None)[source]

Bases: KiCadObject

Footprint text definition token.

The ‘fp_text’ token defines text in a footprint in the format:

(fp_text
    TYPE
    "TEXT"
    POSITION_IDENTIFIER
    [unlocked]
    (layer LAYER_DEFINITION)
    [hide]
    (effects TEXT_EFFECTS)
    (uuid UUID)
)
Parameters:
  • type (str) – Text type (reference | value | user)

  • text (str) – Text content

  • at (FpTextAt) – Position and rotation coordinates

  • unlocked (OptionalFlag | None) – Whether text orientation can be other than upright (optional)

  • layer (Layer) – Layer definition

  • hide (OptionalFlag | None) – Whether text is hidden (optional)

  • effects (Effects) – Text effects

  • uuid (Uuid | None) – Unique identifier

__init__(type='', text='', at=<factory>, unlocked=<factory>, layer=<factory>, hide=<factory>, effects=<factory>, uuid=None)
class FpTextAt(x=0.0, y=None, angle=None)[source]

Bases: KiCadObject

Position identifier token for FpText that supports flexible coordinate formats.

The ‘at’ token for fp_text defines positional coordinates in the format:

(at X [Y] [ANGLE])

Special case: Sometimes only one coordinate is provided like (at 0).

Parameters:
  • x (float) – Horizontal position of the text

  • y (float | None) – Vertical position of the text (optional)

  • angle (float | None) – Rotation angle of the text (optional)

__init__(x=0.0, y=None, angle=None)
class FpTextBox(locked=<factory>, text='', start=None, end=None, pts=None, angle=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>, stroke=None, render_cache=<factory>)[source]

Bases: KiCadObject

Footprint text box definition token.

The ‘fp_text_box’ token defines a rectangle containing line-wrapped text in the format:

(fp_text_box
    [locked]
    "TEXT"
    [(start X Y)]
    [(end X Y)]
    [(pts (xy X Y) (xy X Y) (xy X Y) (xy X Y))]
    [(angle ROTATION)]
    (layer LAYER_DEFINITION)
    (uuid UUID)
    TEXT_EFFECTS
    [STROKE_DEFINITION]
    [(render_cache RENDER_CACHE)]
)
Parameters:
  • locked (OptionalFlag | None) – Whether the text box can be moved (optional)

  • text (str) – Content of the text box

  • start (Start | None) – Top-left corner of cardinally oriented text box (optional)

  • end (End | None) – Bottom-right corner of cardinally oriented text box (optional)

  • pts (Pts | None) – Four corners of non-cardinally oriented text box (optional)

  • angle (KiCadFloat | None) – Rotation of the text box in degrees (optional)

  • layer (Layer) – Layer definition

  • uuid (Uuid) – Unique identifier

  • effects (Effects) – Text effects

  • stroke (Stroke | None) – Stroke definition for optional border (optional)

  • render_cache (KiCadStr | None) – Text rendering cache for TrueType fonts (optional)

__init__(locked=<factory>, text='', start=None, end=None, pts=None, angle=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>, stroke=None, render_cache=<factory>)
class GrArc(start=<factory>, mid=<factory>, end=<factory>, layer=<factory>, width=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Graphical arc definition token.

The ‘gr_arc’ token defines an arc graphic object in the format:

(gr_arc
    (start X Y)
    (mid X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    (uuid UUID)
)
Parameters:
  • start (Start) – Start point coordinates

  • mid (Pos) – Mid point coordinates

  • end (End) – End point coordinates

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • uuid (Uuid) – Unique identifier

__init__(start=<factory>, mid=<factory>, end=<factory>, layer=<factory>, width=<factory>, uuid=<factory>)
class GrBbox(start=<factory>, end=<factory>)[source]

Bases: KiCadObject

Graphical bounding box definition token.

The ‘gr_bbox’ token defines a bounding box inside which annotations will be shown in the format:

(gr_bbox
    (start X Y)
    (end X Y)
)
Parameters:
  • start (Start) – Coordinates of the upper left corner

  • end (End) – Coordinates of the lower right corner

__init__(start=<factory>, end=<factory>)
class GrCircle(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, fill=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Graphical circle definition token.

The ‘gr_circle’ token defines a circle graphic object in the format:

(gr_circle
    (center X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    [(fill yes | no)]
    (uuid UUID)
)
Parameters:
  • center (Center) – Center point coordinates

  • end (End) – End point defining radius

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • fill (OptionalFlag | None) – Fill definition (optional)

  • uuid (Uuid) – Unique identifier

__init__(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, fill=<factory>, uuid=<factory>)
class GrCurve(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)[source]

Bases: FpCurve

Graphical curve derived from footprint curve.

Inherits all fields from FpCurve but uses ‘gr_curve’ token.

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)
class GrLine(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)[source]

Bases: FpLine

Graphical line derived from footprint line.

Inherits all fields from FpLine but uses ‘gr_line’ token.

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)
class GrPoly(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)[source]

Bases: FpPoly

Graphical polygon derived from footprint polygon.

Inherits all fields from FpPoly but uses ‘gr_poly’ token.

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)
class GrRect(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)[source]

Bases: FpRect

Graphical rectangle derived from footprint rectangle.

Inherits all fields from FpRect but uses ‘gr_rect’ token.

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)
class GrText(text='', at=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>)[source]

Bases: KiCadObject

Graphical text definition token.

The ‘gr_text’ token defines text graphic objects in the format:

(gr_text
    "TEXT"
    POSITION_IDENTIFIER
    (layer LAYER_DEFINITION [knockout])
    (uuid UUID)
    (effects TEXT_EFFECTS)
)
Parameters:
  • text (str) – Text content

  • at (At) – Position and rotation coordinates

  • layer (Layer) – Layer definition

  • uuid (Uuid) – Unique identifier

  • effects (Effects) – Text effects

__init__(text='', at=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>)
class GrTextBox(locked=<factory>, text='', start=None, end=None, pts=None, angle=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>, stroke=None, render_cache=<factory>)[source]

Bases: KiCadObject

Graphical text box definition token.

The ‘gr_text_box’ token defines a rectangle containing line-wrapped text in the format:

(gr_text_box
    [locked]
    "TEXT"
    [(start X Y)]
    [(end X Y)]
    [(pts (xy X Y) (xy X Y) (xy X Y) (xy X Y))]
    [(angle ROTATION)]
    (layer LAYER_DEFINITION)
    (uuid UUID)
    TEXT_EFFECTS
    [STROKE_DEFINITION]
    [(render_cache RENDER_CACHE)]
)
Parameters:
  • locked (OptionalFlag | None) – Whether the text box can be moved (optional)

  • text (str) – Content of the text box

  • start (Start | None) – Top-left corner of cardinally oriented text box (optional)

  • end (End | None) – Bottom-right corner of cardinally oriented text box (optional)

  • pts (Pts | None) – Four corners of non-cardinally oriented text box (optional)

  • angle (KiCadFloat | None) – Rotation of the text box in degrees (optional)

  • layer (Layer) – Layer definition

  • uuid (Uuid) – Unique identifier

  • effects (Effects) – Text effects

  • stroke (Stroke | None) – Stroke definition for optional border (optional)

  • render_cache (KiCadStr | None) – Text rendering cache for TrueType fonts (optional)

__init__(locked=<factory>, text='', start=None, end=None, pts=None, angle=<factory>, layer=<factory>, uuid=<factory>, effects=<factory>, stroke=None, render_cache=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class Layer(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)[source]

Bases: KiCadObject

Layer definition token.

The ‘layer’ token defines layer information in the format:

(layer "NAME" | dielectric NUMBER (type "DESCRIPTION")
       [(color "COLOR")] [(thickness THICKNESS)]
       [(material "MATERIAL")] [(epsilon_r VALUE)]
       [(loss_tangent VALUE)])
For simple layer references:

(layer “LAYER_NAME”)

Parameters:
  • name (str) – Layer name or ‘dielectric’

  • number (int | None) – Layer stack number (optional)

  • type (str | None) – Layer type description (optional)

  • color (str | None) – Layer color as string (optional)

  • thickness (float | None) – Layer thickness value (optional)

  • material (str | None) – Material name (optional)

  • epsilon_r (float | None) – Dielectric constant value (optional)

  • loss_tangent (float | None) – Loss tangent value (optional)

__init__(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Pos(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Position definition token.

The ‘pos’ token defines a position in the format: (pos X Y)

Parameters:
  • x (float) – Horizontal position coordinate

  • y (float) – Vertical position coordinate

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Pts(points=<factory>)[source]

Bases: KiCadObject

Coordinate point list definition token.

The ‘pts’ token defines a list of coordinate points in the format: (pts

(xy X Y) … (xy X Y)

)

Where each xy token defines a single X and Y coordinate pair. The number of points is determined by the object type.

Parameters:

points (List[Xy]) – List of 2D coordinate points

__init__(points=<factory>)
class Start(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Start point definition token.

The ‘start’ token defines a start point in the format: (start X Y)

Parameters:
  • x (float) – Horizontal position of the start point

  • y (float) – Vertical position of the start point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Stroke(width=<factory>, type=<factory>, color=None)[source]

Bases: KiCadObject

Stroke definition token.

The ‘stroke’ token defines how the outlines of graphical objects are drawn in the format: (stroke

(width WIDTH) (type TYPE) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • width (KiCadFloat) – Line width specification

  • type (Type) – Stroke line style specification

  • color (Color | None) – Line color specification (optional)

__init__(width=<factory>, type=<factory>, color=None)
class Type(value='')[source]

Bases: KiCadObject

Type definition token.

The ‘type’ token defines a type value in the format: (type VALUE)

Parameters:

value (str) – Type value

__init__(value='')
to_sexpr()[source]

Custom serialization to ensure type values are never quoted.

class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.text_and_documents module

Text and document related elements for KiCad S-expressions.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class AtXY(x=0.0, y=0.0)[source]

Bases: KiCadObject

Position identifier token for elements that only use X and Y coordinates.

The ‘at’ token defines positional coordinates in the format:

(at X Y)

Used for elements like junctions that don’t have rotation.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

__init__(x=0.0, y=0.0)
class Bitmap(name=<factory>, pos=<factory>, scale=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=None, pngdata=<factory>)[source]

Bases: KiCadObject

Bitmap image definition token.

The ‘bitmap’ token defines a bitmap image in the format:

(bitmap
    (name "NAME")
    (pos X Y)
    (scale SCALAR)
    [(repeat COUNT)]
    [(incrx DISTANCE)]
    [(incry DISTANCE)]
    [(comment "COMMENT")]
    (pngdata IMAGE_DATA)
)
Parameters:
  • name (KiCadStr) – Image name

  • pos (Pos) – Position coordinates

  • scale (KiCadFloat) – Scale factor

  • repeat (KiCadInt | None) – Repeat count (optional)

  • incrx (KiCadFloat | None) – X increment distance (optional)

  • incry (KiCadFloat | None) – Y increment distance (optional)

  • comment (str | None) – Image comment (optional)

  • pngdata (Pngdata) – PNG image data

__init__(name=<factory>, pos=<factory>, scale=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=None, pngdata=<factory>)
class Comment(number=1, text='')[source]

Bases: KiCadObject

Comment definition token.

The ‘comment’ token defines document comments in the format:

(comment N "COMMENT")

Where N is a number from 1 to 9.

Parameters:
  • number (int) – Comment number (1-9)

  • text (str) – Comment text

__init__(number=1, text='')
class Data(hex_bytes=<factory>)[source]

Bases: KiCadObject

Data definition token.

The ‘data’ token defines hexadecimal byte data in the format:

(data XX1 ... XXN)

Where XXN represents hexadecimal bytes separated by spaces, with a maximum of 32 bytes per data token.

Parameters:

hex_bytes (List[str]) – Hexadecimal byte values (up to 32 bytes)

__init__(hex_bytes=<factory>)
class End(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

End point definition token.

The ‘end’ token defines an end point in the format:

(end X Y)
Parameters:
  • x (float) – Horizontal position of the end point

  • y (float) – Vertical position of the end point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Font(face=<factory>, size=None, thickness=<factory>, bold=<factory>, italic=<factory>, color=None)[source]

Bases: KiCadObject

Font definition token.

The ‘font’ token defines font properties in the format: (font [face “FONT_NAME”] [size WIDTH HEIGHT] [thickness THICKNESS] [bold] [italic])

Parameters:
  • face (KiCadStr | None) – Font face specification (optional)

  • size (Size | None) – Font size (optional)

  • thickness (KiCadFloat | None) – Font thickness (optional)

  • bold (OptionalFlag | None) – Bold flag (optional)

  • italic (OptionalFlag | None) – Italic flag (optional)

  • color (Color | None) – Font color (optional)

__init__(face=<factory>, size=None, thickness=<factory>, bold=<factory>, italic=<factory>, color=None)
class Group(name='', id=<factory>, members=None)[source]

Bases: KiCadObject

Group definition token.

The ‘group’ token defines a group of objects in the format:

(group
    "NAME"
    (id UUID)
    (members UUID1 ... UUIDN)
)
Parameters:
  • name (str) – Group name

  • id (KiCadStr) – Group unique identifier

  • members (Members | None) – List of member UUIDs (optional)

__init__(name='', id=<factory>, members=None)
class Image(at=<factory>, scale=<factory>, uuid=None, data=None, locked=<factory>)[source]

Bases: KiCadObject

Image definition token.

The ‘image’ token defines an image object in PCB files in the format:

(image (at X Y) (scale FACTOR) (uuid UUID) (data ...))
Parameters:
  • at (AtXY) – Position

  • scale (KiCadFloat | None) – Scale factor (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • data (Data | None) – Image data (optional)

  • locked (OptionalFlag | None) – Whether image is locked (optional)

__init__(at=<factory>, scale=<factory>, uuid=None, data=None, locked=<factory>)
class Justify(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)[source]

Bases: KiCadObject

Text justification definition token.

The ‘justify’ token defines text alignment and mirroring in the format:

(justify [left | right | center] [top | bottom | center] [mirror])
Parameters:
  • left (OptionalFlag | None) – Left horizontal justification flag (optional)

  • right (OptionalFlag | None) – Right horizontal justification flag (optional)

  • top (OptionalFlag | None) – Top vertical justification flag (optional)

  • bottom (OptionalFlag | None) – Bottom vertical justification flag (optional)

  • center (OptionalFlag | None) – Center justification flag (horizontal or vertical) (optional)

  • mirror (OptionalFlag | None) – Mirror text flag (optional)

__init__(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class KicadWks(version=<factory>, generator=<factory>, generator_version=<factory>, page=<factory>, title_block=None, setup=None, rect=<factory>, line=<factory>, tbtext=<factory>, elements=<factory>)[source]

Bases: KiCadObject

KiCad worksheet definition token.

The ‘kicad_wks’ token defines worksheet format information in the format:

(kicad_wks
    (version VERSION)
    (generator GENERATOR)
    ;; contents of the schematic file...
)
Parameters:
  • version (KiCadInt | None) – Format version (optional)

  • generator (KiCadStr | None) – Generator name (optional)

  • generator_version (KiCadStr | None) – Generator version (optional)

  • page (KiCadStr | None) – Page settings (optional)

  • title_block (TitleBlock | None) – Title block (optional)

  • setup (WksSetup | None) – Worksheet setup (optional)

  • rect (List[WksRect] | None) – List of rectangles (optional)

  • line (List[WksLine] | None) – List of lines (optional)

  • tbtext (List[WksTbText] | None) – List of text blocks (optional)

  • elements (List[Any] | None) – List of worksheet elements (optional)

__init__(version=<factory>, generator=<factory>, generator_version=<factory>, page=<factory>, title_block=None, setup=None, rect=<factory>, line=<factory>, tbtext=<factory>, elements=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for worksheet operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_wks file format.

Parameters:
  • file_path (str) – Path to write the .kicad_wks file

  • encoding (str) – File encoding (default: utf-8)

class Members(uuids=<factory>)[source]

Bases: KiCadObject

Group members definition token.

The ‘members’ token defines the members of a group in the format:

(members UUID1 UUID2 ... UUIDN)
Parameters:

uuids (List[Uuid]) – List of member UUIDs

__init__(uuids=<factory>)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Paper(size=None, width=None, height=None, portrait=<factory>)[source]

Bases: KiCadObject

Paper settings definition token.

The ‘paper’ token defines paper size and orientation in the format:

(paper PAPER_SIZE | WIDTH HEIGHT [portrait])

Where PAPER_SIZE can be: A0, A1, A2, A3, A4, A5, A, B, C, D, E.

Parameters:
  • size (str | None) – Standard paper size (optional)

  • width (float | None) – Custom paper width (optional)

  • height (float | None) – Custom paper height (optional)

  • portrait (OptionalFlag | None) – Whether paper is in portrait mode (optional)

__init__(size=None, width=None, height=None, portrait=<factory>)
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class Pngdata(data_lines=<factory>)[source]

Bases: KiCadObject

PNG data definition token.

The ‘pngdata’ token defines PNG image data in the format:

(pngdata
    (data XX1 ... XXN)
    (data XX1 ... XXN)
    ...
)

Where each data line contains up to 32 hexadecimal bytes.

Parameters:

data_lines (List[Data]) – List of data token objects containing hexadecimal bytes

__init__(data_lines=<factory>)
class Pos(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Position definition token.

The ‘pos’ token defines a position in the format: (pos X Y)

Parameters:
  • x (float) – Horizontal position coordinate

  • y (float) – Vertical position coordinate

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Size(width=0.0, height=0.0)[source]

Bases: KiCadObject

Size definition token.

The ‘size’ token defines width and height dimensions in the format: (size WIDTH HEIGHT)

Parameters:
  • width (float) – Width dimension

  • height (float) – Height dimension

__init__(width=0.0, height=0.0)
class Start(x=0.0, y=0.0, corner=None)[source]

Bases: KiCadObject

Start point definition token.

The ‘start’ token defines a start point in the format: (start X Y)

Parameters:
  • x (float) – Horizontal position of the start point

  • y (float) – Vertical position of the start point

  • corner (str | None) – Corner reference (optional)

__init__(x=0.0, y=0.0, corner=None)
class Tbtext(text='', name=<factory>, pos=<factory>, font=None, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=None)[source]

Bases: KiCadObject

Title block text definition token.

The ‘tbtext’ token defines text elements in the title block in the format:

(tbtext
    "TEXT"
    (name "NAME")
    (pos X Y [CORNER])
    (font [(size WIDTH HEIGHT)] [bold] [italic])
    [(repeat COUNT)]
    [(incrx DISTANCE)]
    [(incry DISTANCE)]
    [(comment "COMMENT")]
)
Parameters:
  • text (str) – Text content

  • name (KiCadStr) – Text element name

  • pos (Pos) – Position coordinates

  • font (Font | None) – Font settings (optional)

  • repeat (KiCadInt | None) – Repeat count for incremental text (optional)

  • incrx (KiCadFloat | None) – Repeat distance on X axis (optional)

  • incry (KiCadFloat | None) – Repeat distance on Y axis (optional)

  • comment (str | None) – Comment for the text object (optional)

__init__(text='', name=<factory>, pos=<factory>, font=None, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=None)
class Textsize(size=<factory>)[source]

Bases: KiCadObject

Text size definition token.

The ‘textsize’ token defines text size in the format:

(textsize WIDTH HEIGHT)
Parameters:

size (Size) – Text size (width and height)

__init__(size=<factory>)
class TitleBlock(title=<factory>, date=<factory>, rev=<factory>, company=<factory>, comments=<factory>)[source]

Bases: KiCadObject

Title block definition token.

The ‘title_block’ token defines the document title block in the format:

(title_block
    (title "TITLE")
    (date "DATE")
    (rev "REVISION")
    (company "COMPANY_NAME")
    (comment N "COMMENT")
)
Parameters:
  • title (KiCadStr | None) – Document title (optional)

  • date (KiCadStr | None) – Document date (optional)

  • rev (KiCadStr | None) – Document revision (optional)

  • company (KiCadStr | None) – Company name (optional)

  • comments (List[Comment] | None) – List of comments (optional)

__init__(title=<factory>, date=<factory>, rev=<factory>, company=<factory>, comments=<factory>)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class WksLine(name=None, start=<factory>, end=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>)[source]

Bases: KiCadObject

Worksheet line definition token.

Parameters:
  • name (str | None) – Line name (optional)

  • start (Start) – Start position

  • end (End) – End position

  • repeat (KiCadInt | None) – Repeat count (optional)

  • incrx (KiCadFloat | None) – X increment (optional)

  • incry (KiCadFloat | None) – Y increment (optional)

__init__(name=None, start=<factory>, end=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>)
class WksRect(name=None, start=<factory>, end=<factory>, comment=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>, linewidth=<factory>)[source]

Bases: KiCadObject

Worksheet rectangle definition token.

Parameters:
  • name (str | None) – Rectangle name (optional)

  • start (Start) – Start position

  • end (End) – End position

  • comment (KiCadStr | None) – Comment (optional)

  • repeat (KiCadInt | None) – Repeat count (optional)

  • incrx (KiCadFloat | None) – X increment (optional)

  • incry (KiCadFloat | None) – Y increment (optional)

  • linewidth (KiCadFloat | None) – Line width (optional)

__init__(name=None, start=<factory>, end=<factory>, comment=<factory>, repeat=<factory>, incrx=<factory>, incry=<factory>, linewidth=<factory>)
class WksSetup(textsize=None, linewidth=<factory>, textlinewidth=<factory>, left_margin=<factory>, right_margin=<factory>, top_margin=<factory>, bottom_margin=<factory>)[source]

Bases: KiCadObject

Worksheet setup definition token.

Parameters:
  • textsize (WksTextsize | None) – Text size (optional)

  • linewidth (KiCadFloat | None) – Line width (optional)

  • textlinewidth (KiCadFloat | None) – Text line width (optional)

  • left_margin (KiCadFloat | None) – Left margin (optional)

  • right_margin (KiCadFloat | None) – Right margin (optional)

  • top_margin (KiCadFloat | None) – Top margin (optional)

  • bottom_margin (KiCadFloat | None) – Bottom margin (optional)

__init__(textsize=None, linewidth=<factory>, textlinewidth=<factory>, left_margin=<factory>, right_margin=<factory>, top_margin=<factory>, bottom_margin=<factory>)
class WksTbText(text='', name=<factory>, pos=<factory>, font=None, justify=None, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=<factory>)[source]

Bases: KiCadObject

Worksheet text block definition token.

Parameters:
  • text (str) – Text content

  • name (KiCadStr | None) – Text name (optional)

  • pos (Pos) – Text position

  • font (Font | None) – Font settings (optional)

  • justify (Justify | None) – Text justification (optional)

  • repeat (KiCadInt | None) – Repeat count (optional)

  • incrx (KiCadFloat | None) – X increment (optional)

  • incry (KiCadFloat | None) – Y increment (optional)

  • comment (KiCadStr | None) – Comment (optional)

__init__(text='', name=<factory>, pos=<factory>, font=None, justify=None, repeat=<factory>, incrx=<factory>, incry=<factory>, comment=<factory>)
class WksTextsize(width=1.0, height=1.0)[source]

Bases: KiCadObject

Worksheet text size definition token.

Parameters:
  • width (float) – Text width

  • height (float) – Text height

__init__(width=1.0, height=1.0)
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

PCB Components

kicadfiles.pad_and_drill module

Pad and drill related elements for KiCad S-expressions.

class AllowTwoSegments(value=True)[source]

Bases: KiCadObject

Allow two segments definition token for teardrops.

The ‘allow_two_segments’ token defines whether two segments are allowed in the format:

(allow_two_segments yes|no)
Parameters:

value (bool) – Whether two segments are allowed

__init__(value=True)
class Anchor(pad_shape=PadShape.RECT)[source]

Bases: KiCadObject

Anchor pad shape definition for custom pads.

The ‘anchor’ token defines the anchor pad shape of a custom pad in the format:

(anchor PAD_SHAPE)
Parameters:

pad_shape (PadShape) – Anchor pad shape (rect or circle)

__init__(pad_shape=PadShape.RECT)
class AtXY(x=0.0, y=0.0)[source]

Bases: KiCadObject

Position identifier token for elements that only use X and Y coordinates.

The ‘at’ token defines positional coordinates in the format:

(at X Y)

Used for elements like junctions that don’t have rotation.

Parameters:
  • x (float) – Horizontal position of the object

  • y (float) – Vertical position of the object

__init__(x=0.0, y=0.0)
class Chamfer(corners=<factory>)[source]

Bases: KiCadObject

Chamfer corner definition token for pads.

The ‘chamfer’ token defines which corners of a rectangular pad get chamfered in the format:

(chamfer CORNER_LIST)

Valid chamfer corner attributes are top_left, top_right, bottom_left, and bottom_right.

Parameters:

corners (List[str]) – List of corners to chamfer

__init__(corners=<factory>)
class CurvedEdges(value=False)[source]

Bases: KiCadObject

Curved edges definition token for teardrops.

The ‘curved_edges’ token defines whether edges are curved in the format:

(curved_edges yes|no)
Parameters:

value (bool) – Whether edges are curved

__init__(value=False)
class Drill(diameter=0.0, oval=<factory>, width=None, offset=None)[source]

Bases: KiCadObject

Drill definition token for pads.

The ‘drill’ token defines the drill attributes for a footprint pad in the format:

(drill
    [oval]
    DIAMETER
    [WIDTH]
    [(offset X Y)]
)
Parameters:
  • diameter (float) – Drill diameter

  • oval (OptionalFlag | None) – Whether the drill is oval instead of round (optional)

  • width (float | None) – Width of the slot for oval drills (optional)

  • offset (Offset | None) – Drill offset coordinates from the center of the pad (optional)

__init__(diameter=0.0, oval=<factory>, width=None, offset=None)
class Enabled(value=True)[source]

Bases: KiCadObject

Enabled definition token for teardrops.

The ‘enabled’ token defines whether teardrops are enabled in the format:

(enabled yes|no)
Parameters:

value (bool) – Whether teardrops are enabled

__init__(value=True)
class GrArc(start=<factory>, mid=<factory>, end=<factory>, layer=<factory>, width=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Graphical arc definition token.

The ‘gr_arc’ token defines an arc graphic object in the format:

(gr_arc
    (start X Y)
    (mid X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    (uuid UUID)
)
Parameters:
  • start (Start) – Start point coordinates

  • mid (Pos) – Mid point coordinates

  • end (End) – End point coordinates

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • uuid (Uuid) – Unique identifier

__init__(start=<factory>, mid=<factory>, end=<factory>, layer=<factory>, width=<factory>, uuid=<factory>)
class GrCircle(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, fill=<factory>, uuid=<factory>)[source]

Bases: KiCadObject

Graphical circle definition token.

The ‘gr_circle’ token defines a circle graphic object in the format:

(gr_circle
    (center X Y)
    (end X Y)
    (layer LAYER_DEFINITION)
    (width WIDTH)
    [(fill yes | no)]
    (uuid UUID)
)
Parameters:
  • center (Center) – Center point coordinates

  • end (End) – End point defining radius

  • layer (Layer) – Layer definition

  • width (KiCadFloat) – Line width

  • fill (OptionalFlag | None) – Fill definition (optional)

  • uuid (Uuid) – Unique identifier

__init__(center=<factory>, end=<factory>, layer=<factory>, width=<factory>, fill=<factory>, uuid=<factory>)
class GrCurve(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)[source]

Bases: FpCurve

Graphical curve derived from footprint curve.

Inherits all fields from FpCurve but uses ‘gr_curve’ token.

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, locked=<factory>)
class GrLine(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)[source]

Bases: FpLine

Graphical line derived from footprint line.

Inherits all fields from FpLine but uses ‘gr_line’ token.

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, uuid=None, stroke=None, locked=<factory>)
class GrPoly(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)[source]

Bases: FpPoly

Graphical polygon derived from footprint polygon.

Inherits all fields from FpPoly but uses ‘gr_poly’ token.

__init__(pts=<factory>, layer=<factory>, width=<factory>, tstamp=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=None)
class GrRect(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)[source]

Bases: FpRect

Graphical rectangle derived from footprint rectangle.

Inherits all fields from FpRect but uses ‘gr_rect’ token.

__init__(start=<factory>, end=<factory>, layer=<factory>, width=<factory>, stroke=None, fill=<factory>, locked=<factory>, uuid=<factory>)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class Layers(layers=<factory>)[source]

Bases: KiCadObject

Layer list definition token.

The ‘layers’ token defines a list of layer names in the format:

(layers "F.Cu" "F.Paste" "F.Mask")
(layers "*.Cu" "*.Mask" "F.SilkS")

Used for pad layers, via layers, and other layer specifications.

layers

List of layer names

Type:

List[str]

Parameters:

layers (List[str]) – List of layer names

__init__(layers=<factory>)
class Net(number=0, name='')[source]

Bases: KiCadObject

Net connection definition token.

The ‘net’ token defines the net connection in the format:

(net ORDINAL "NET_NAME")
Parameters:
  • number (int) – Net number

  • name (str) – Net name

__init__(number=0, name='')
class Offset(x=0.0, y=0.0)[source]

Bases: KiCadObject

Offset definition token.

The ‘offset’ token defines an offset position in the format: (offset X Y)

Parameters:
  • x (float) – Horizontal offset coordinate

  • y (float) – Vertical offset coordinate

__init__(x=0.0, y=0.0)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Options(clearance=<factory>, anchor=None)[source]

Bases: KiCadObject

Custom pad options definition token.

The ‘options’ token defines options for custom pads in the format:

(options
    (clearance CLEARANCE_TYPE)
    (anchor PAD_SHAPE)
)

Valid clearance types are outline and convexhull. Valid anchor pad shapes are rect and circle.

Parameters:
  • clearance (KiCadStr | None) – Clearance type for custom pad (optional)

  • anchor (Anchor | None) – Anchor pad shape (optional)

__init__(clearance=<factory>, anchor=None)
class Pad(number='', type=PadType.THRU_HOLE, shape=PadShape.CIRCLE, at=<factory>, size=<factory>, layers=<factory>, drill=None, property=None, locked=<factory>, remove_unused_layer=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, roundrect_rratio=<factory>, chamfer_ratio=None, chamfer=<factory>, net=None, uuid=None, pinfunction=None, pintype=None, die_length=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_margin_ratio=None, clearance=None, zone_connect=None, thermal_width=None, thermal_gap=None, options=None, primitives=None, teardrops=None)[source]

Bases: KiCadObject

Footprint pad definition token.

The ‘pad’ token defines a pad in a footprint with comprehensive properties in the format:

(pad "NUMBER" TYPE SHAPE POSITION_IDENTIFIER [(locked)] (size X Y)
     [(drill DRILL_DEFINITION)] (layers "CANONICAL_LAYER_LIST") ...)

Note

Field order follows KiCad documentation, not dataclass conventions. Required fields after optional fields violate dataclass ordering.

Parameters:
  • number (str) – Pad number or name

  • type (PadType) – Pad type

  • shape (PadShape) – Pad shape

  • at (AtXY) – Position and rotation

  • size (Size) – Pad dimensions

  • layers (Layers) – Layer list

  • drill (Drill | None) – Drill definition (optional)

  • property (str | None) – Pad property (optional)

  • locked (OptionalFlag | None) – Whether pad is locked (optional)

  • remove_unused_layer (OptionalFlag | None) – Remove unused layers flag (optional)

  • remove_unused_layers (OptionalFlag | None) – Remove unused layers flag (newer format) (optional)

  • keep_end_layers (OptionalFlag | None) – Keep end layers flag (optional)

  • roundrect_rratio (KiCadFloat | None) – Round rectangle corner ratio (optional)

  • chamfer_ratio (float | None) – Chamfer ratio (optional)

  • chamfer (List[str] | None) – Chamfer corners (optional)

  • net (Net | None) – Net connection (optional)

  • uuid (Uuid | None) – Unique identifier (optional)

  • pinfunction (str | None) – Pin function name (optional)

  • pintype (str | None) – Pin type (optional)

  • die_length (float | None) – Die length (optional)

  • solder_mask_margin (float | None) – Solder mask margin (optional)

  • solder_paste_margin (float | None) – Solder paste margin (optional)

  • solder_paste_margin_ratio (float | None) – Solder paste margin ratio (optional)

  • clearance (float | None) – Clearance value (optional)

  • zone_connect (ZoneConnection | None) – Zone connection type (optional)

  • thermal_width (float | None) – Thermal width (optional)

  • thermal_gap (float | None) – Thermal gap (optional)

  • options (Options | None) – Custom pad options (optional)

  • primitives (Primitives | None) – Custom pad primitives (optional)

  • teardrops (Teardrops | None) – Teardrop settings (optional)

__init__(number='', type=PadType.THRU_HOLE, shape=PadShape.CIRCLE, at=<factory>, size=<factory>, layers=<factory>, drill=None, property=None, locked=<factory>, remove_unused_layer=<factory>, remove_unused_layers=<factory>, keep_end_layers=<factory>, roundrect_rratio=<factory>, chamfer_ratio=None, chamfer=<factory>, net=None, uuid=None, pinfunction=None, pintype=None, die_length=None, solder_mask_margin=None, solder_paste_margin=None, solder_paste_margin_ratio=None, clearance=None, zone_connect=None, thermal_width=None, thermal_gap=None, options=None, primitives=None, teardrops=None)
class PadShape(*values)[source]

Bases: Enum

Pad shapes for footprints.

CIRCLE = 'circle'
CUSTOM = 'custom'
OVAL = 'oval'
RECT = 'rect'
ROUNDRECT = 'roundrect'
TRAPEZOID = 'trapezoid'
class PadType(*values)[source]

Bases: Enum

Pad types for footprints.

CONNECT = 'connect'
NP_THRU_HOLE = 'np_thru_hole'
SMD = 'smd'
THRU_HOLE = 'thru_hole'
class Pads(pads=<factory>)[source]

Bases: KiCadObject

Container for multiple pads.

The ‘pads’ token defines a collection of pads in the format:

(pads
    (pad ...)
    ...
)
Parameters:

pads (List[Pad]) – List of pads

__init__(pads=<factory>)
class PreferZoneConnections(value=True)[source]

Bases: KiCadObject

Prefer zone connections definition token for teardrops.

The ‘prefer_zone_connections’ token defines whether zone connections are preferred in the format:

(prefer_zone_connections yes|no)
Parameters:

value (bool) – Whether zone connections are preferred

__init__(value=True)
class Primitives(elements=<factory>, width=<factory>, fill=<factory>)[source]

Bases: KiCadObject

Custom pad primitives definition token.

The ‘primitives’ token defines drawing objects for custom pads in the format:

(primitives
    (gr_poly ...)
    (gr_line ...)
    (gr_circle ...)
    (gr_arc ...)
    (gr_rect ...)
    (gr_curve ...)
    ...
)
Parameters:
__init__(elements=<factory>, width=<factory>, fill=<factory>)
class Shape(shape=PadShape.CIRCLE)[source]

Bases: KiCadObject

Pad shape definition token.

The ‘shape’ token defines the shape of a pad in the format:

(shape SHAPE_TYPE)

Valid pad shapes are circle, rect, oval, trapezoid, roundrect, or custom.

Parameters:

shape (PadShape) – Pad shape type

__init__(shape=PadShape.CIRCLE)
class Size(width=0.0, height=0.0)[source]

Bases: KiCadObject

Size definition token.

The ‘size’ token defines width and height dimensions in the format: (size WIDTH HEIGHT)

Parameters:
  • width (float) – Width dimension

  • height (float) – Height dimension

__init__(width=0.0, height=0.0)
class Teardrops(best_length_ratio=<factory>, max_length=<factory>, best_width_ratio=<factory>, max_width=<factory>, curved_edges=<factory>, filter_ratio=<factory>, enabled=<factory>, allow_two_segments=<factory>, prefer_zone_connections=<factory>)[source]

Bases: KiCadObject

Teardrops definition token for pads.

The ‘teardrops’ token defines teardrop settings in the format:

(teardrops
    (best_length_ratio RATIO)
    (max_length LENGTH)
    (best_width_ratio RATIO)
    (max_width WIDTH)
    (curved_edges yes|no)
    (filter_ratio RATIO)
    (enabled yes|no)
    (allow_two_segments yes|no)
    (prefer_zone_connections yes|no)
)
Parameters:
__init__(best_length_ratio=<factory>, max_length=<factory>, best_width_ratio=<factory>, max_width=<factory>, curved_edges=<factory>, filter_ratio=<factory>, enabled=<factory>, allow_two_segments=<factory>, prefer_zone_connections=<factory>)
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class ZoneConnect(connection_type=ZoneConnection.INHERITED)[source]

Bases: KiCadObject

Zone connection definition token.

The ‘zone_connect’ token defines how a pad connects to filled zones in the format:

(zone_connect CONNECTION_TYPE)

Valid connection types are integer values from 0 to 3: - 0: Pad not connected to zone - 1: Pad connected using thermal relief - 2: Pad connected using solid fill

Parameters:

connection_type (ZoneConnection) – Zone connection type

__init__(connection_type=ZoneConnection.INHERITED)
class ZoneConnection(*values)[source]

Bases: Enum

Zone connection types for pads.

INHERITED = 0
NONE = 3
SOLID = 1
THERMAL_RELIEF = 2
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

kicadfiles.zone_system module

Zone system elements for KiCad S-expressions - copper zones and keepout areas.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class ConnectPads(connection_type=None, clearance=<factory>)[source]

Bases: KiCadObject

Connect pads definition token for zones.

The ‘connect_pads’ token defines pad connection type and clearance in the format:

(connect_pads [CONNECTION_TYPE] (clearance CLEARANCE))
Parameters:
  • connection_type (str | None) – Pad connection type (thru_hole_only | full | no) (optional)

  • clearance (KiCadFloat) – Pad clearance

__init__(connection_type=None, clearance=<factory>)
class Copperpour(value=ZoneKeepoutSetting.NOT_ALLOWED)[source]

Bases: KiCadObject

Copper pour definition token.

The ‘copperpour’ token defines copper pour properties in the format:

(copperpour VALUE)

where VALUE can be: not_allowed, allowed

Parameters:

value (ZoneKeepoutSetting) – Copper pour setting

__init__(value=ZoneKeepoutSetting.NOT_ALLOWED)
class Fill(type=None, color=None)[source]

Bases: KiCadObject

Fill definition token.

The ‘fill’ token defines how schematic and symbol library graphical items are filled in the format: (fill

(type none | outline | background) (color R G B A)

)

This represents the nested structure exactly as it appears in the S-expression files.

Parameters:
  • type (Type | None) – Fill type specification (optional)

  • color (Color | None) – Fill color specification (optional)

__init__(type=None, color=None)
class FillSegments(segments=<factory>)[source]

Bases: KiCadObject

Fill segments definition token.

The ‘fill_segments’ token defines zone fill segments in the format:

(fill_segments ...)
Parameters:

segments (List[Any]) – List of fill segments

__init__(segments=<factory>)
class FilledPolygon(layer='', pts=<factory>)[source]

Bases: KiCadObject

Filled polygon definition token.

The ‘filled_polygon’ token defines the polygons used to fill the zone in the format:

(filled_polygon
    (layer LAYER_DEFINITION)
    COORDINATE_POINT_LIST
)
Parameters:
  • layer (str) – Layer the zone fill resides on

  • pts (Pts) – List of polygon X/Y coordinates used to fill the zone

__init__(layer='', pts=<factory>)
class FilledSegments(layer='', segments=<factory>)[source]

Bases: KiCadObject

Filled segments definition token.

The ‘filled_segments’ token defines segments used to fill the zone in the format:

(fill_segments
    (layer LAYER_DEFINITION)
    COORDINATED_POINT_LIST
)
Parameters:
  • layer (str) – Layer the zone fill resides on

  • segments (List[Pts]) – List of X and Y coordinates of segments used to fill the zone

__init__(layer='', segments=<factory>)
class Hatch(style=HatchStyle.EDGE, pitch=0.5)[source]

Bases: KiCadObject

Zone hatch display definition token.

The ‘hatch’ token defines zone outline display style and pitch in the format:

(hatch STYLE PITCH)
Parameters:
  • style (HatchStyle) – Hatch display style

  • pitch (float) – Hatch pitch distance

__init__(style=HatchStyle.EDGE, pitch=0.5)
class HatchOrientation(angle=<factory>)[source]

Bases: KiCadObject

Hatch orientation definition token.

The ‘hatch_orientation’ token defines the angle for hatch lines in the format:

(hatch_orientation ANGLE)
Parameters:

angle (KiCadFloat) – Hatch line angle in degrees

__init__(angle=<factory>)
class HatchStyle(*values)[source]

Bases: Enum

Zone hatch display styles.

EDGE = 'edge'
FULL = 'full'
NONE = 'none'
class Keepout(tracks=ZoneKeepoutSetting.NOT_ALLOWED, vias=ZoneKeepoutSetting.NOT_ALLOWED, pads=ZoneKeepoutSetting.NOT_ALLOWED, copperpour=ZoneKeepoutSetting.NOT_ALLOWED, footprints=ZoneKeepoutSetting.NOT_ALLOWED)[source]

Bases: KiCadObject

Keepout zone definition token.

The ‘keepout’ token defines which objects should be kept out of the zone in the format:

(keepout
    (tracks KEEPOUT)
    (vias KEEPOUT)
    (pads KEEPOUT)
    (copperpour KEEPOUT)
    (footprints KEEPOUT)
)
Parameters:
  • tracks (ZoneKeepoutSetting) – Whether tracks should be excluded (allowed | not_allowed)

  • vias (ZoneKeepoutSetting) – Whether vias should be excluded (allowed | not_allowed)

  • pads (ZoneKeepoutSetting) – Whether pads should be excluded (allowed | not_allowed)

  • copperpour (ZoneKeepoutSetting) – Whether copper pours should be excluded (allowed | not_allowed)

  • footprints (ZoneKeepoutSetting) – Whether footprints should be excluded (allowed | not_allowed)

__init__(tracks=ZoneKeepoutSetting.NOT_ALLOWED, vias=ZoneKeepoutSetting.NOT_ALLOWED, pads=ZoneKeepoutSetting.NOT_ALLOWED, copperpour=ZoneKeepoutSetting.NOT_ALLOWED, footprints=ZoneKeepoutSetting.NOT_ALLOWED)
class KiCadFloat(token_name='', value=0.0, required=True)[source]

Bases: KiCadPrimitive

Float wrapper for KiCad values.

__init__(token_name='', value=0.0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class Mode(mode=ZoneFillMode.SOLID)[source]

Bases: KiCadObject

Fill mode definition token.

The ‘mode’ token defines the zone fill mode in the format:

(mode MODE)
Parameters:

mode (ZoneFillMode) – Fill mode

__init__(mode=ZoneFillMode.SOLID)
class OptionalFlag(token, is_token=False, token_value=None, __found__=False)[source]

Bases: object

Enhanced flag container for optional tokens in S-expressions.

Can handle: 1. Simple presence flags: (locked) -> token=”locked”, is_token=True, token_value=None 2. Tokens with values: (locked yes) -> token=”locked”, is_token=True, token_value=”yes” 3. Simple strings: “locked” -> token=”locked”, is_token=False, token_value=None

__bool__()[source]

Boolean conversion - returns the logical boolean value based on token_value.

__eq__(other)[source]

Equality comparison for OptionalFlag objects.

__hash__()[source]

Hash implementation - required when implementing __eq__.

__init__(token, is_token=False, token_value=None, __found__=False)
__repr__()[source]

Developer-friendly representation.

__str__()[source]

Clean string representation.

classmethod create_bool_flag(token)[source]

Create a simple boolean flag (presence indicates True).

to_sexpr()[source]

Convert back to S-expression format for round-trip.

class Polygon(pts=<factory>, uuid=None)[source]

Bases: KiCadObject

Polygon definition token.

The ‘polygon’ token defines a polygon with multiple points in the format:

(polygon (pts (xy X Y) (xy X Y) ...) (uuid UUID))
Parameters:
  • pts (Pts) – Polygon vertex points

  • uuid (Uuid | None) – Unique identifier (optional)

__init__(pts=<factory>, uuid=None)
class Pts(points=<factory>)[source]

Bases: KiCadObject

Coordinate point list definition token.

The ‘pts’ token defines a list of coordinate points in the format: (pts

(xy X Y) … (xy X Y)

)

Where each xy token defines a single X and Y coordinate pair. The number of points is determined by the object type.

Parameters:

points (List[Xy]) – List of 2D coordinate points

__init__(points=<factory>)
class Smoothing(style=SmoothingStyle.NONE)[source]

Bases: KiCadObject

Zone smoothing definition token.

The ‘smoothing’ token defines corner smoothing style in the format:

(smoothing STYLE)
Parameters:

style (SmoothingStyle) – Corner smoothing style

__init__(style=SmoothingStyle.NONE)
class SmoothingStyle(*values)[source]

Bases: Enum

Zone corner smoothing styles.

CHAMFER = 'chamfer'
FILLET = 'fillet'
NONE = 'none'
class Uuid(value='')[source]

Bases: KiCadObject

UUID identifier token.

The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)

Parameters:

value (str) – UUID value

__init__(value='')
classmethod new_id()[source]

Generate a new UUID identifier.

Returns:

New Uuid object with a generated UUID value

Return type:

Uuid

class Zone(hatch=<factory>, connect_pads=<factory>, fill=<factory>, polygon=<factory>, net=0, net_name='', layer='', uuid=<factory>, min_thickness=0.0, name=None, priority=None, filled_areas_thickness=<factory>, keepout=None, filled_polygons=<factory>, filled_segments=<factory>)[source]

Bases: KiCadObject

Zone definition token.

The ‘zone’ token defines a zone on the board or footprint in the format:

(zone
    (net NET_NUMBER)
    (net_name "NET_NAME")
    (layer LAYER_DEFINITION)
    (uuid UUID)
    [(name "NAME")]
    (hatch STYLE PITCH)
    [(priority PRIORITY)]
    (connect_pads [CONNECTION_TYPE] (clearance CLEARANCE))
    (min_thickness THICKNESS)
    [(filled_areas_thickness no)]
    [ZONE_KEEPOUT_SETTINGS]
    ZONE_FILL_SETTINGS
    (polygon COORDINATE_POINT_LIST)
    [ZONE_FILL_POLYGONS...]
    [ZONE_FILL_SEGMENTS...]
)
Parameters:
  • hatch (Hatch) – Hatch settings

  • connect_pads (ConnectPads) – Pad connection settings

  • fill (Fill) – Fill settings

  • polygon (Polygon) – Zone outline polygon

  • net (int) – Net number

  • net_name (str) – Net name

  • layer (str) – Layer name

  • uuid (Uuid) – Unique identifier

  • min_thickness (float) – Minimum thickness

  • name (str | None) – Zone name (optional)

  • priority (int | None) – Zone priority (optional)

  • filled_areas_thickness (OptionalFlag | None) – Filled areas thickness flag (optional)

  • keepout (Keepout | None) – Keepout settings (optional)

  • filled_polygons (List[FilledPolygon] | None) – List of fill polygons (optional)

  • filled_segments (List[FilledSegments] | None) – List of fill segments (optional)

__init__(hatch=<factory>, connect_pads=<factory>, fill=<factory>, polygon=<factory>, net=0, net_name='', layer='', uuid=<factory>, min_thickness=0.0, name=None, priority=None, filled_areas_thickness=<factory>, keepout=None, filled_polygons=<factory>, filled_segments=<factory>)
class ZoneFillMode(*values)[source]

Bases: Enum

Zone fill modes.

HATCHED = 'hatched'
SOLID = 'solid'
class ZoneKeepoutSetting(*values)[source]

Bases: Enum

Zone keepout settings.

ALLOWED = 'allowed'
NOT_ALLOWED = 'not_allowed'
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

Utilities

kicadfiles.sexpdata module

class Brackets(*args)[source]

Bases: Delimiters

Outputs an Iterable or Mapping with square brackets.

Selectively make a container an array:

>>> dumps(Brackets(list(range(5))))
'[0 1 2 3 4]'
>>> dumps(Brackets(dict(a=1)))
'[:a 1]'
closer: str = ']'
opener: str = '['
exception ExpectClosingBracket(got, expect, position=None)[source]

Bases: SExpError

__init__(got, expect, position=None)[source]
exception ExpectNothing(got, position=None)[source]

Bases: SExpError

__init__(got, position=None)[source]
exception ExpectSExp(position=None)[source]

Bases: SExpError

__init__(position=None)[source]
exception InvalidEscape(escape_char, position=None)[source]

Bases: SExpError

__init__(escape_char, position=None)[source]
class Parens(*args)[source]

Bases: Delimiters

Outputs an Iterable or Mapping with parentheses.

By default Iterables and Mappings output with parentheses.

>>> dumps(range(5))
'(0 1 2 3 4)'
>>> dumps(dict(a=1))
'(:a 1)'

Selectively override the tuple_as=’array’ default parameter:

>>> dumps((0, Parens((1, 2, 3)), 4), tuple_as='array')
'[0 (1 2 3) 4]'
closer: str = ')'
opener: str = '('
class Position(line=1, column=1, offset=0)[source]

Bases: object

Represents a position in the source text with line and column numbers.

__init__(line=1, column=1, offset=0)[source]
class Quoted(x)[source]

Bases: Quoted

exception SExpError(message, position=None)[source]

Bases: Exception

Base class for S-expression parsing errors with position information.

__init__(message, position=None)[source]
class String(object, position=None)[source]

Bases: object

__hash__()[source]
>>> D = {'a': 1, String('a'): 2, Symbol('a'): 3}
>>> len(D)
3
__init__(object, position=None)[source]
classmethod quote(string)[source]
classmethod unquote(string)[source]
class Symbol(object, position=None)[source]

Bases: String

exception UnterminatedString(position=None)[source]

Bases: SExpError

__init__(position=None)[source]
car(obj)[source]

Alias of obj[0].

>>> car(loads('(a . b)'))
Symbol('a')
>>> car(loads('(a b)'))
Symbol('a')
cdr(obj)[source]

cdr-like function.

>>> cdr(loads('(a . b)'))
Symbol('b')
>>> cdr(loads('(a b)'))
[Symbol('b')]
>>> cdr(loads('(a . (b))'))
[Symbol('b')]
>>> cdr(loads('(a)'))
[]
>>> cdr(loads('(a . nil)'))
[]
dump(obj, filelike, **kwds)[source]

Write obj as an S-expression into given stream filelike.

Parameters:
  • obj – A Python object.

  • filelike – A text stream object.

See dumps() for valid keyword arguments.

>>> import io
>>> fp = io.StringIO()
>>> dump(('a', 'b'), fp, str_as='symbol')
>>> print(fp.getvalue())
(a b)
dumps(obj, **kwds)[source]

Convert python object into an S-expression.

Parameters:

obj – A Python object.

Keyword Arguments:
  • str_as – How string should be interpreted. Default is 'string'.

  • tuple_as – How tuple should be interpreted. Default is 'list'.

  • true_as – How True should be interpreted. Default is 't'

  • false_as – How False should be interpreted. Default is '()'

  • none_as – How None should be interpreted. Default is '()'

  • pretty_print – Format output as a tree. Default is False

  • indent_as – String to use for each level of tree indentation. Default is '  '

Basic usage:

>>> print(dumps(['a', 'b']))
("a" "b")
>>> print(dumps(['a', 'b'], str_as='symbol'))
(a b)
>>> print(dumps(dict(a=1)))
(:a 1)
>>> ProperTuple = namedtuple('ProperTuple', 'k')
>>> print(dumps(ProperTuple('v')))
(:k "v")
>>> print(dumps([None, True, False, ()]))
(() t () ())
>>> print(dumps([None, True, False, ()],
...             none_as='null', true_as='#t', false_as='#f'))
(null #t #f ())
>>> print(dumps(('a', 'b')))
("a" "b")
>>> print(dumps(('a', 'b'), tuple_as='array'))
["a" "b"]

More verbose usage:

>>> print(dumps([Symbol('a'), Symbol('b')]))
(a b)
>>> print(dumps(Symbol('a')))
a
>>> print(dumps([Symbol('a'), Quoted(Symbol('b'))]))
(a 'b)
>>> print(dumps([Symbol('a'), Quoted([Symbol('b')])]))
(a '(b))
load(filelike, **kwds)[source]

Load object from S-expression stored in filelike.

Parameters:

filelike – A text stream object.

See loads() for valid keyword arguments.

>>> import io
>>> fp = io.StringIO()
>>> sexp = [Symbol('a'), Symbol('b')]   # let's dump and load this object
>>> dump(sexp, fp)
>>> _ = fp.seek(0)
>>> load(fp) == sexp
True
loads(string, **kwds)[source]

Load object from S-expression string.

Parameters:

string – String containing an S-expression.

Keyword Arguments:
  • nil – A symbol interpreted as an empty list. Default is 'nil'.

  • true – A symbol interpreted as True. Default is 't'.

  • false – A symbol interpreted as False. Default is None.

  • line_comment – Beginning of line comment. Default is ';'.

>>> loads("(a b)")
[Symbol('a'), Symbol('b')]
>>> loads("a")
Symbol('a')
>>> loads("(a 'b)")
[Symbol('a'), Quoted(Symbol('b'))]
>>> loads("(a '(b))")
[Symbol('a'), Quoted([Symbol('b')])]
>>> loads('''
... ;; This is a line comment.
... ("a" "b")  ; this is also a comment.
... ''')
['a', 'b']
>>> loads('''
... # This is a line comment.
... ("a" "b")  # this is also a comment.
... ''', line_comment='#')
['a', 'b']

nil is converted to an empty list by default. You can use keyword argument nil to change what symbol must be interpreted as nil:

>>> loads("nil")
[]
>>> loads("null", nil='null')
[]
>>> loads("nil", nil=None)
Symbol('nil')

t is converted to True by default. You can use keyword argument true to change what symbol must be converted to True.:

>>> loads("t")
True
>>> loads("#t", true='#t')
True
>>> loads("t", true=None)
Symbol('t')

No symbol is converted to False by default. You can use keyword argument false to convert a symbol to False.

>>> loads("#f")
Symbol('#f')
>>> loads("#f", false='#f')
False
>>> loads("nil", false='nil', nil=None)
False
parse(string, **kwds)[source]

Parse s-expression.

>>> parse("(a b)")
[[Symbol('a'), Symbol('b')]]
>>> parse("a")
[Symbol('a')]
>>> parse("(a 'b)")
[[Symbol('a'), Quoted(Symbol('b'))]]
>>> parse("(a '(b))")
[[Symbol('a'), Quoted([Symbol('b')])]]

kicadfiles.sexpr_parser module

S-Expression Parser for KiCad files

This module provides a simplified approach to parsing S-expressions. Only contains the functions actually used by the kicadfiles package.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class SExprParser(sexpr)[source]

Bases: object

Minimal S-Expression parser with usage tracking always enabled.

__init__(sexpr)[source]

Initialize parser with an S-expression.

Parameters:

sexpr (List[Any]) – Parsed S-expression as nested lists/atoms

classmethod from_string(sexpr_string)[source]

Create parser from S-expression string.

Parameters:

sexpr_string (str) – String containing S-expression data

Returns:

New parser instance

Return type:

SExprParser

get_unused_parameters()[source]

Get list of unused parameters.

Returns:

List of unused parameters (excluding token name at index 0)

Return type:

List[Any]

mark_used(index)[source]

Mark a parameter index as used.

Parameters:

index (int) – Index in sexpr that was accessed

SExprValue

alias of Any

cast(typ, val)[source]

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

dumps(obj, **kwds)[source]

Convert python object into an S-expression.

Parameters:

obj – A Python object.

Keyword Arguments:
  • str_as – How string should be interpreted. Default is 'string'.

  • tuple_as – How tuple should be interpreted. Default is 'list'.

  • true_as – How True should be interpreted. Default is 't'

  • false_as – How False should be interpreted. Default is '()'

  • none_as – How None should be interpreted. Default is '()'

  • pretty_print – Format output as a tree. Default is False

  • indent_as – String to use for each level of tree indentation. Default is '  '

Basic usage:

>>> print(dumps(['a', 'b']))
("a" "b")
>>> print(dumps(['a', 'b'], str_as='symbol'))
(a b)
>>> print(dumps(dict(a=1)))
(:a 1)
>>> ProperTuple = namedtuple('ProperTuple', 'k')
>>> print(dumps(ProperTuple('v')))
(:k "v")
>>> print(dumps([None, True, False, ()]))
(() t () ())
>>> print(dumps([None, True, False, ()],
...             none_as='null', true_as='#t', false_as='#f'))
(null #t #f ())
>>> print(dumps(('a', 'b')))
("a" "b")
>>> print(dumps(('a', 'b'), tuple_as='array'))
["a" "b"]

More verbose usage:

>>> print(dumps([Symbol('a'), Symbol('b')]))
(a b)
>>> print(dumps(Symbol('a')))
a
>>> print(dumps([Symbol('a'), Quoted(Symbol('b'))]))
(a 'b)
>>> print(dumps([Symbol('a'), Quoted([Symbol('b')])]))
(a '(b))
loads(string, **kwds)[source]

Load object from S-expression string.

Parameters:

string – String containing an S-expression.

Keyword Arguments:
  • nil – A symbol interpreted as an empty list. Default is 'nil'.

  • true – A symbol interpreted as True. Default is 't'.

  • false – A symbol interpreted as False. Default is None.

  • line_comment – Beginning of line comment. Default is ';'.

>>> loads("(a b)")
[Symbol('a'), Symbol('b')]
>>> loads("a")
Symbol('a')
>>> loads("(a 'b)")
[Symbol('a'), Quoted(Symbol('b'))]
>>> loads("(a '(b))")
[Symbol('a'), Quoted([Symbol('b')])]
>>> loads('''
... ;; This is a line comment.
... ("a" "b")  ; this is also a comment.
... ''')
['a', 'b']
>>> loads('''
... # This is a line comment.
... ("a" "b")  # this is also a comment.
... ''', line_comment='#')
['a', 'b']

nil is converted to an empty list by default. You can use keyword argument nil to change what symbol must be interpreted as nil:

>>> loads("nil")
[]
>>> loads("null", nil='null')
[]
>>> loads("nil", nil=None)
Symbol('nil')

t is converted to True by default. You can use keyword argument true to change what symbol must be converted to True.:

>>> loads("t")
True
>>> loads("#t", true='#t')
True
>>> loads("t", true=None)
Symbol('t')

No symbol is converted to False by default. You can use keyword argument false to convert a symbol to False.

>>> loads("#f")
Symbol('#f')
>>> loads("#f", false='#f')
False
>>> loads("nil", false='nil', nil=None)
False
sexpr_to_str(sexpr)[source]

Convert S-expression to string representation.

Parameters:

sexpr (List[Any]) – S-expression to serialize

Returns:

String representation of the S-expression

Raises:

ValueError – If sexpr cannot be serialized

Return type:

str

str_to_sexpr(content)[source]

Convert string content to S-expression.

Parameters:

content (str) – String content containing S-expression data

Returns:

Parsed S-expression as nested lists/atoms

Raises:

ValueError – If content cannot be parsed as valid S-expression

Return type:

List[Any]

kicadfiles.json_base_element module

Base class for JSON-based KiCad file parsing.

This module provides automatic JSON serialization/deserialization for KiCad files like .kicad_pro project files. It mirrors the functionality of base_element.py but is designed specifically for JSON format files.

Key Features: - Automatic type-aware parsing based on dataclass field definitions - Round-trip preservation with exact structure preservation option - Nested object handling for complex data structures - File I/O methods with proper encoding and extension validation

class ABC[source]

Bases: object

Helper class that provides a standard way to create an ABC using inheritance.

class Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class JsonObject[source]

Bases: ABC

Base class for JSON-based KiCad objects.

This class provides similar functionality to KiCadObject but for JSON format files like .kicad_pro project files. It automatically handles serialization/deserialization based on dataclass field definitions.

Features: - Automatic JSON parsing based on dataclass field definitions - Round-trip preservation with preserve_original option - Type-aware serialization/deserialization for nested objects - File I/O methods with extension validation and encoding support - Recursive handling of Optional, List, and nested JsonObject types

Usage:

@dataclass class MyKiCadFile(JsonObject):

version: int = 1 data: Optional[Dict[str, Any]] = None

# Parse from file obj = MyKiCadFile.from_file(“file.json”)

# Parse from dictionary obj = MyKiCadFile.from_dict({“version”: 2, “data”: {…}})

# Export with exact round-trip preservation data = obj.to_dict(preserve_original=True)

__init__()
classmethod from_dict(data)[source]

Create instance from dictionary data.

Parameters:

data (Dict[str, Any]) – Dictionary containing the data

Returns:

Instance of the class

Return type:

T

classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from JSON file.

Parameters:
  • file_path (str) – Path to JSON file

  • strictness (ParseStrictness) – Parse strictness level (not used for JSON, kept for compatibility)

  • encoding (str) – File encoding (default: utf-8)

Returns:

Instance of the class

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

  • ValueError – If the file contains invalid JSON

  • UnicodeDecodeError – If the file encoding is incorrect

Return type:

T

classmethod from_str(json_string, strictness=ParseStrictness.STRICT)[source]

Parse from JSON string.

Parameters:
  • json_string (str) – JSON content as string

  • strictness (ParseStrictness) – Parse strictness level (not used for JSON, kept for compatibility)

Returns:

Instance of the class

Raises:

ValueError – If the JSON string is invalid

Return type:

T

save_to_file(file_path, encoding='utf-8', preserve_original=False)[source]

Save to JSON file format.

Parameters:
  • file_path (str) – Path to write the JSON file

  • encoding (str) – File encoding (default: utf-8)

  • preserve_original (bool) – Whether to preserve original structure

to_dict(preserve_original=False)[source]

Convert to dictionary format.

Parameters:

preserve_original (bool) – If True and original data exists, return updated original data preserving the exact structure

Returns:

Dictionary representation

Return type:

Dict[str, Any]

to_json_str(pretty_print=True, preserve_original=False)[source]

Convert to JSON string format.

Parameters:
  • pretty_print (bool) – Whether to format JSON with indentation

  • preserve_original (bool) – If True, preserve original structure for exact round-trip

Returns:

JSON string representation

Return type:

str

class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class TypeVar

Bases: object

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

fields(class_or_instance)[source]

Return a tuple describing the fields of this dataclass.

Accepts a dataclass or an instance of one. Tuple elements are of type Field.

get_args(tp)[source]

Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed.

Examples:

>>> T = TypeVar('T')
>>> assert get_args(Dict[str, int]) == (str, int)
>>> assert get_args(int) == ()
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
>>> assert get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)[source]

Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types.

Examples:

>>> P = ParamSpec('P')
>>> assert get_origin(Literal[42]) is Literal
>>> assert get_origin(int) is None
>>> assert get_origin(ClassVar[int]) is ClassVar
>>> assert get_origin(Generic) is Generic
>>> assert get_origin(Generic[T]) is Generic
>>> assert get_origin(Union[T, int]) is Union
>>> assert get_origin(List[Tuple[T, T]][int]) is list
>>> assert get_origin(P.args) is P

kicadfiles.design_rules module

Design rules elements for KiCad S-expressions - design rule constraint system.

class ConstraintType(*values)[source]

Bases: Enum

Design rule constraint types.

ANNULAR_WIDTH = 'annular_width'
ASSERTION = 'assertion'
BLIND_VIA_RATIO = 'blind_via_ratio'
CLEARANCE = 'clearance'
CONNECTION_WIDTH = 'connection_width'
COURTYARD_CLEARANCE = 'courtyard_clearance'
CREEPAGE = 'creepage'
DIFF_PAIR_GAP = 'diff_pair_gap'
DIFF_PAIR_UNCOUPLED = 'diff_pair_uncoupled'
DISALLOW = 'disallow'
EDGE_CLEARANCE = 'edge_clearance'
HOLE_CLEARANCE = 'hole_clearance'
HOLE_SIZE = 'hole_size'
HOLE_TO_HOLE = 'hole_to_hole'
LENGTH = 'length'
MICRO_VIA_DIAMETER = 'micro_via_diameter'
MICRO_VIA_DRILL = 'micro_via_drill'
MIN_RESOLVED_SPOKES = 'min_resolved_spokes'
PHYSICAL_CLEARANCE = 'physical_clearance'
PHYSICAL_HOLE_CLEARANCE = 'physical_hole_clearance'
SILK_CLEARANCE = 'silk_clearance'
SKEW = 'skew'
TEXT_HEIGHT = 'text_height'
TEXT_THICKNESS = 'text_thickness'
THERMAL_RELIEF_GAP = 'thermal_relief_gap'
THERMAL_SPOKE_WIDTH = 'thermal_spoke_width'
TRACK_WIDTH = 'track_width'
VIA_DIAMETER = 'via_diameter'
VIA_DRILL = 'via_drill'
ZONE_CONNECTION = 'zone_connection'
class DesignRule(name='', severity=None, layer=<factory>, condition=<factory>, priority=<factory>, constraints=<factory>)[source]

Bases: KiCadObject

Design rule definition token.

The ‘rule’ token defines a complete design rule in the format:

(rule NAME
    [(severity SEVERITY)]
    [(layer LAYER_NAME)]
    [(condition EXPRESSION)]
    [(priority PRIORITY_NUMBER)]
    (constraint CONSTRAINT_TYPE [CONSTRAINT_ARGUMENTS])
    [(constraint CONSTRAINT_TYPE [CONSTRAINT_ARGUMENTS])]...
)
Parameters:
  • name (str) – Rule name

  • severity (DesignRuleSeverity | None) – Severity level (optional)

  • layer (KiCadStr | None) – Layer specification (optional)

  • condition (KiCadStr | None) – Conditional expression (optional)

  • priority (KiCadInt | None) – Rule priority (optional)

  • constraints (List[DesignRuleConstraint]) – List of constraint definitions

__init__(name='', severity=None, layer=<factory>, condition=<factory>, priority=<factory>, constraints=<factory>)
class DesignRuleConstraint(constraint_type=ConstraintType.CLEARANCE, min_constraint=<factory>, opt_constraint=<factory>, max_constraint=<factory>, disallow_item=None)[source]

Bases: KiCadObject

Design rule constraint definition token.

The ‘constraint’ token defines a constraint with optional min/opt/max values in the format:

(constraint CONSTRAINT_TYPE [(min VALUE)] [(opt VALUE)] [(max VALUE)])
(constraint disallow ITEM_TYPE)
Parameters:
  • constraint_type (ConstraintType) – Type of constraint

  • min_constraint (KiCadStr | None) – Minimum value constraint (optional)

  • opt_constraint (KiCadStr | None) – Optimal value constraint (optional)

  • max_constraint (KiCadStr | None) – Maximum value constraint (optional)

  • disallow_item (str | None) – Item type to disallow (optional)

__init__(constraint_type=ConstraintType.CLEARANCE, min_constraint=<factory>, opt_constraint=<factory>, max_constraint=<factory>, disallow_item=None)
class DesignRuleSeverity(level=SeverityLevel.ERROR)[source]

Bases: KiCadObject

Design rule severity level token.

The ‘severity’ token defines the severity level for rule violations in the format:

(severity error | warning | ignore)
Parameters:

level (SeverityLevel) – Severity level

__init__(level=SeverityLevel.ERROR)
class KiCadDesignRules(version=<factory>, rules=<factory>)[source]

Bases: KiCadObject

KiCad design rules file definition.

The design rules file contains version information and a list of rules in the format:

(version VERSION)
RULES...

Note: This is different from other KiCad files - it doesn’t have a root token like ‘kicad_dru’, instead it starts directly with version and rules.

Parameters:
  • version (KiCadInt) – File format version

  • rules (List[DesignRule] | None) – List of design rules (optional)

__init__(version=<factory>, rules=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from S-expression file - convenience method for design rules operations.

Design rules files (.kicad_dru) have a special format without root token wrapping. This method handles the preprocessing needed for the parser.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for design rules.

This method automatically handles .kicad_dru format preprocessing.

save_to_file(file_path, encoding='utf-8')[source]

Save to .kicad_dru file format.

Parameters:
  • file_path (str) – Path to write the .kicad_dru file

  • encoding (str) – File encoding (default: utf-8)

to_dru_str()[source]

Convert to .kicad_dru format string (without root token wrapper).

This method produces the native .kicad_dru file format.

class KiCadInt(token_name='', value=0, required=True)[source]

Bases: KiCadPrimitive

Integer wrapper for KiCad values.

__init__(token_name='', value=0, required=True)
class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class KiCadStr(token_name='', value='', required=True)[source]

Bases: KiCadPrimitive

String wrapper for KiCad values.

__init__(token_name='', value='', required=True)
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class SeverityLevel(*values)[source]

Bases: Enum

Design rule severity levels.

ERROR = 'error'
EXCLUSION = 'exclusion'
IGNORE = 'ignore'
WARNING = 'warning'
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.

sexpr_to_str(sexpr)[source]

Convert S-expression to string representation.

Parameters:

sexpr (List[Any]) – S-expression to serialize

Returns:

String representation of the S-expression

Raises:

ValueError – If sexpr cannot be serialized

Return type:

str

kicadfiles.library_tables module

Library table classes for KiCad library management.

This module provides dataclasses for parsing and managing KiCad library tables: - FpLibTable: Footprint library table (fp-lib-table) - SymLibTable: Symbol library table (sym-lib-table)

Both table types share the same structure with library entries containing: - name: Library identifier - type: Library type (typically “KiCad”) - uri: Path to library - options: Additional options - descr: Human readable description

class FpLibTable(version=7, libraries=<factory>)[source]

Bases: KiCadObject

Footprint library table (fp-lib-table file).

Contains version information and a list of footprint library entries.

Parameters:
  • version (int) – Table format version

  • libraries (List[LibraryEntry]) – List of library entries

__init__(version=7, libraries=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from fp-lib-table file - convenience method for library table operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to fp-lib-table file format.

Parameters:
  • file_path (str) – Path to write the fp-lib-table file

  • encoding (str) – File encoding (default: utf-8)

class KiCadObject[source]

Bases: ABC

Base class for KiCad S-expression objects with cursor-based parsing.

__init__()
__post_init__()[source]

Validate token name is defined.

__str__()[source]

String representation showing only non-None values (except for required fields).

classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT)[source]

Single public entry point - parser created once here.

classmethod from_str(sexpr_string, strictness=ParseStrictness.STRICT)[source]

Parse from S-expression string - convenience method for better clarity.

to_sexpr()[source]

Convert to S-expression using simple field iteration.

to_sexpr_str(_indent_level=0)[source]

Convert to KiCad-formatted S-expression string using to_sexpr() with custom formatting.

Parameters:

_indent_level (int) – Internal parameter for recursion depth

Returns:

Formatted S-expression string

Return type:

str

class LibraryEntry(name='', type='', uri='', options='', descr='')[source]

Bases: KiCadObject

A single library entry in a library table.

Represents a (lib …) entry with name, type, uri, options, and description.

Parameters:
  • name (str) – Library name/identifier

  • type (str) – Library type (e.g., ‘KiCad’)

  • uri (str) – Path to library

  • options (str) – Additional options

  • descr (str) – Human readable description

__init__(name='', type='', uri='', options='', descr='')
class ParseStrictness(*values)[source]

Bases: Enum

Parser strictness levels for error handling.

FAILSAFE = 'failsafe'
SILENT = 'silent'
STRICT = 'strict'
class SymLibTable(version=7, libraries=<factory>)[source]

Bases: KiCadObject

Symbol library table (sym-lib-table file).

Contains version information and a list of symbol library entries.

Parameters:
  • version (int) – Table format version

  • libraries (List[LibraryEntry]) – List of library entries

__init__(version=7, libraries=<factory>)
classmethod from_file(file_path, strictness=ParseStrictness.STRICT, encoding='utf-8')[source]

Parse from sym-lib-table file - convenience method for library table operations.

save_to_file(file_path, encoding='utf-8')[source]

Save to sym-lib-table file format.

Parameters:
  • file_path (str) – Path to write the sym-lib-table file

  • encoding (str) – File encoding (default: utf-8)

dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]

Add dunder methods based on the fields defined in the class.

Examines PEP 526 __annotations__ to determine fields.

If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.

field(*, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>)[source]

Return an object to identify dataclass fields.

default is the default value of the field. default_factory is a 0-argument function called to initialize a field’s value. If init is true, the field will be a parameter to the class’s __init__() function. If repr is true, the field will be included in the object’s repr(). If hash is true, the field will be included in the object’s hash(). If compare is true, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. If kw_only is true, the field will become a keyword-only parameter to __init__().

It is an error to specify both default and default_factory.