Base Classes and Utilities
This section documents the core base classes, enums, and utility modules that form the foundation of the KiCadFiles library.
Core Base Classes
kicadfiles.base_element module
Base class for S-expression based KiCad objects. Provides parsing and serialization functionality for KiCad S-expression format.
S-expression parser for KiCad objects.
Architecture: - Unified token handling via __token_name__ in SExpressionBase - Central parsing utilities in ParseCursor - Type-based field classification (PRIMITIVE vs SEXPR_BASE) - Clean separation between instance fields and list containers - Field metadata as single source of truth for required/optional behavior
- class NamedFloat(token='', value=0.0)[source]
Bases:
NamedValueFloat wrapper for named values.
- __init__(token='', value=0.0)
- class NamedInt(token='', value=0)[source]
Bases:
NamedValueInteger wrapper for named values.
- __init__(token='', value=0)
- class NamedObject[source]
Bases:
SExpressionBaseBase class for named S-expression objects.
Subclasses should define __token_name__ as ClassVar[str].
- __init__()
- classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT, cursor=None)[source]
Parse from S-expression.
- class NamedString(token='', value='')[source]
Bases:
NamedValueString wrapper for named values.
- __init__(token='', value='')
- class ParseStrictness(*values)[source]
Bases:
EnumParser strictness levels for error handling.
- FAILSAFE = 'failsafe'
- SILENT = 'silent'
- STRICT = 'strict'
- class SymbolValue(token='')[source]
Bases:
TokenBaseSimple flag for optional symbols.
Represents standalone tokens like ‘oval’, ‘locked’ without values. Does not consume positional slots during parsing.
- __init__(token='')
- class TokenFlag(token='', token_value=None)[source]
Bases:
TokenBaseOptional flag with optional value.
- Formats:
(token) -> token=”token”, token_value=None (token value) -> token=”token”, token_value=”value”
- __call__(new_value=None)[source]
Allow calling the flag to update its value.
This enables convenient syntax like: pcb.legacy_teardrops(“no”) instead of: pcb.legacy_teardrops = TokenFlag(“legacy_teardrops”, “no”)
- Parameters:
new_value (str | None) – New token value to set
- Returns:
Self for method chaining
- Return type:
- __init__(token='', token_value=None)
kicadfiles.json_base_element module
Base class for JSON based KiCad objects (e.g., project files). Provides parsing and serialization functionality for KiCad JSON format.
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:
objectHelper class that provides a standard way to create an ABC using inheritance.
- class Any(*args, **kwargs)[source]
Bases:
objectSpecial 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:
ABCBase class for JSON-based KiCad objects.
This class provides similar functionality to NamedObject 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:
EnumParser strictness levels for error handling.
- FAILSAFE = 'failsafe'
- SILENT = 'silent'
- STRICT = 'strict'
- class TypeVar
Bases:
objectType 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=Trueis passed. Manually created type variables may be explicitly marked covariant or contravariant by passingcovariant=Trueorcontravariant=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
Basic Types
kicadfiles.base_types module
Common basic types used across KiCad files (At, Size, Layer, Stroke, etc.).
Base types for KiCad S-expressions - fundamental elements with no cross-dependencies.
- class Anchor(pad_shape=PadShape.RECT)[source]
Bases:
NamedObjectAnchor 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 Any(*args, **kwargs)[source]
Bases:
objectSpecial 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:
NamedObjectPosition 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:
NamedObjectPosition 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 BoardLayers(layer_defs=<factory>)[source]
Bases:
NamedObjectBoard layer definitions for kicad_pcb files.
Stores layer definitions as raw lists:
(layers (0 "F.Cu" signal) (2 "B.Cu" signal) ...)
Use get_layer(index) to parse a specific layer as LayerDefinition if needed.
- __init__(layer_defs=<factory>)
- class Center(x=0.0, y=0.0)[source]
Bases:
NamedObjectCenter 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:
NamedObjectColor 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=<factory>, justify=<factory>, hide=<factory>, href=<factory>)[source]
Bases:
NamedObjectText 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) – Font definition (optional)
justify (Justify) – Text justification (optional)
hide (TokenFlag) – Whether text is hidden (optional)
href (NamedString) – Hyperlink reference (optional)
- __init__(font=<factory>, justify=<factory>, hide=<factory>, href=<factory>)
- class End(x=0.0, y=0.0, corner=None)[source]
Bases:
NamedObjectEnd 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=<factory>, color=<factory>)[source]
Bases:
NamedObjectFill 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:
- __init__(type=<factory>, color=<factory>)
- class Font(face=<factory>, size=<factory>, thickness=<factory>, bold=<factory>, italic=<factory>, color=<factory>)[source]
Bases:
NamedObjectFont definition token.
The ‘font’ token defines font properties in the format: (font [face “FONT_NAME”] [size WIDTH HEIGHT] [thickness THICKNESS] [bold] [italic])
- Parameters:
face (NamedString) – Font face specification (optional)
size (Size | None) – Font size (optional)
thickness (NamedFloat) – Font thickness (optional)
bold (TokenFlag) – Bold flag (optional)
italic (TokenFlag) – Italic flag (optional)
color (Color) – Font color (optional)
- __init__(face=<factory>, size=<factory>, thickness=<factory>, bold=<factory>, italic=<factory>, color=<factory>)
- class Justify(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)[source]
Bases:
NamedObjectText justification definition token.
The ‘justify’ token defines text alignment and mirroring in the format:
(justify [left | right | center] [top | bottom | center] [mirror])
- Parameters:
left (TokenFlag) – Left horizontal justification flag (optional)
right (TokenFlag) – Right horizontal justification flag (optional)
top (TokenFlag) – Top vertical justification flag (optional)
bottom (TokenFlag) – Bottom vertical justification flag (optional)
center (TokenFlag) – Center justification flag (horizontal or vertical) (optional)
mirror (TokenFlag) – Mirror text flag (optional)
- __init__(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>, center=<factory>, mirror=<factory>)
- class Layer(name='', number=None, type=None, color=None, thickness=None, material=None, epsilon_r=None, loss_tangent=None)[source]
Bases:
NamedObjectLayer 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 LayerDefinition(*args, **kwargs)[source]
Bases:
objectBoard layer definition entry (no token name).
Individual layer definition within a ‘layers’ token in PCB files:
(0 "F.Cu" signal) (9 "F.Adhes" user "F.Adhesive") (31 "F.CrtYd" user "F.Courtyard")
Stores the raw list internally and provides properties for access.
- Parameters:
data – Raw layer data as list [ordinal, name, type, user_name?]
- property canonical_name: str
Canonical layer name.
- property layer_type: str
Layer type (signal, user, power, mixed, jumper).
- property ordinal: int
Layer ordinal number.
- property user_name: str | None
User-defined layer name (optional).
- class Layers(layers=<factory>)[source]
Bases:
NamedObjectLayer 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:
NamedObjectMid 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 NamedFloat(token='', value=0.0)[source]
Bases:
NamedValueFloat wrapper for named values.
- __init__(token='', value=0.0)
- class NamedObject[source]
Bases:
SExpressionBaseBase class for named S-expression objects.
Subclasses should define __token_name__ as ClassVar[str].
- __init__()
- classmethod from_sexpr(sexpr, strictness=ParseStrictness.STRICT, cursor=None)[source]
Parse from S-expression.
- class NamedString(token='', value='')[source]
Bases:
NamedValueString wrapper for named values.
- __init__(token='', value='')
- class Offset(x=0.0, y=0.0)[source]
Bases:
NamedObjectOffset 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 PadShape(*values)[source]
Bases:
EnumPad 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:
NamedObjectPosition 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=<factory>, effects=<factory>, unlocked=<factory>, layer=<factory>, uuid=<factory>, hide=<factory>)[source]
Bases:
NamedObjectProperty 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 (NamedString) – Property ID (optional)
at (At) – Position and rotation (optional)
effects (Effects) – Text effects (optional)
unlocked (TokenFlag) – Whether property is unlocked (optional)
layer (Layer) – Layer assignment (optional)
uuid (Uuid) – Unique identifier (optional)
hide (TokenFlag) – Hide property flag (optional)
- __init__(key='', value='', id=<factory>, at=<factory>, effects=<factory>, unlocked=<factory>, layer=<factory>, uuid=<factory>, hide=<factory>)
- class Pts(points=<factory>)[source]
Bases:
NamedObjectCoordinate 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:
NamedObjectSize 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:
NamedObjectStart 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=<factory>)[source]
Bases:
NamedObjectStroke 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 (NamedFloat) – Line width specification
type (Type) – Stroke line style specification
color (Color) – Line color specification (optional)
- __init__(width=<factory>, type=<factory>, color=<factory>)
- class StrokeType(*values)[source]
Bases:
EnumValid 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=<factory>, effects=<factory>, exclude_from_sim=<factory>, uuid=<factory>)[source]
Bases:
NamedObjectText content definition token.
The ‘text’ token defines text content in the format: (text “TEXT_CONTENT”
(at X Y [ANGLE]) (effects EFFECTS)
)
- Parameters:
- __init__(content='', at=<factory>, effects=<factory>, exclude_from_sim=<factory>, uuid=<factory>)
- class TokenFlag(token='', token_value=None)[source]
Bases:
TokenBaseOptional flag with optional value.
- Formats:
(token) -> token=”token”, token_value=None (token value) -> token=”token”, token_value=”value”
- __call__(new_value=None)[source]
Allow calling the flag to update its value.
This enables convenient syntax like: pcb.legacy_teardrops(“no”) instead of: pcb.legacy_teardrops = TokenFlag(“legacy_teardrops”, “no”)
- Parameters:
new_value (str | None) – New token value to set
- Returns:
Self for method chaining
- Return type:
- __init__(token='', token_value=None)
- class Type(value='')[source]
Bases:
NamedObjectType definition token.
The ‘type’ token defines a type value in the format: (type VALUE)
- Parameters:
value (str) – Type value
- __init__(value='')
- class UnquotedToken[source]
Bases:
strMarker class for tokens that should not be quoted in serialization.
- class Uuid(value='')[source]
Bases:
NamedObjectUUID identifier token.
The ‘uuid’ token defines a universally unique identifier in the format: (uuid UUID_VALUE)
- Parameters:
value (str) – UUID value
- __init__(value='')
- class Xy(x=0.0, y=0.0)[source]
Bases:
NamedObject2D 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:
NamedObject3D 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
Enumeration types for various KiCad properties (PadType, PadShape, StrokeType, etc.).
Common enumeration types for KiCad S-expressions.
- class ClearanceType(*values)[source]
Bases:
EnumCustom pad clearance types.
- CONVEXHULL = 'convexhull'
- OUTLINE = 'outline'
- class ConstraintType(*values)[source]
Bases:
EnumDesign 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:
objectCreate 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:
EnumFill types for graphical objects.
- BACKGROUND = 'background'
- COLOR = 'color'
- NONE = 'none'
- OUTLINE = 'outline'
- class FootprintTextType(*values)[source]
Bases:
EnumFootprint text types.
- REFERENCE = 'reference'
- USER = 'user'
- VALUE = 'value'
- class HatchStyle(*values)[source]
Bases:
EnumZone hatch display styles.
- EDGE = 'edge'
- FULL = 'full'
- NONE = 'none'
- class JustifyHorizontal(*values)[source]
Bases:
EnumHorizontal text justification.
- CENTER = 'center'
- LEFT = 'left'
- RIGHT = 'right'
- class JustifyVertical(*values)[source]
Bases:
EnumVertical text justification.
- BOTTOM = 'bottom'
- CENTER = 'center'
- TOP = 'top'
- class LabelShape(*values)[source]
Bases:
EnumLabel 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:
EnumPCB layer types.
- JUMPER = 'jumper'
- MIXED = 'mixed'
- POWER = 'power'
- SIGNAL = 'signal'
- USER = 'user'
- class PadShape(*values)[source]
Bases:
EnumPad shapes for footprints.
- CIRCLE = 'circle'
- CUSTOM = 'custom'
- OVAL = 'oval'
- RECT = 'rect'
- ROUNDRECT = 'roundrect'
- TRAPEZOID = 'trapezoid'
- class PadType(*values)[source]
Bases:
EnumPad types for footprints.
- CONNECT = 'connect'
- NP_THRU_HOLE = 'np_thru_hole'
- SMD = 'smd'
- THRU_HOLE = 'thru_hole'
- class PinElectricalType(*values)[source]
Bases:
EnumPin 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:
EnumPin 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:
EnumDesign rule severity levels.
- ERROR = 'error'
- EXCLUSION = 'exclusion'
- IGNORE = 'ignore'
- WARNING = 'warning'
- class SmoothingStyle(*values)[source]
Bases:
EnumZone corner smoothing styles.
- CHAMFER = 'chamfer'
- FILLET = 'fillet'
- NONE = 'none'
- class StrokeType(*values)[source]
Bases:
EnumValid 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:
EnumVia types for PCB.
- BLIND_BURIED = 'blind_buried'
- MICRO = 'micro'
- THROUGH = 'through'
- class ZoneConnection(*values)[source]
Bases:
EnumZone connection types for pads.
- INHERITED = 0
- NONE = 3
- SOLID = 1
- THERMAL_RELIEF = 2
Parser and Data Utilities
kicadfiles.sexpr_parser module
S-expression parser for KiCad file formats.
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:
objectSpecial 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:
objectMinimal 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:
- 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
Falseindent_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']
nilis 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')
tis 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
kicadfiles.sexpdata module
Low-level S-expression data structures and utilities.
- class Brackets(*args)[source]
Bases:
DelimitersOutputs 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 = '['
- class Parens(*args)[source]
Bases:
DelimitersOutputs 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:
objectRepresents a position in the source text with line and column numbers.
- exception SExpError(message, position=None)[source]
Bases:
ExceptionBase class for S-expression parsing errors with position information.
- 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
Falseindent_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']
nilis 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')
tis 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
Helper Utilities
kicadfiles.templates module
Helper class for creating empty/minimal KiCad files with sensible defaults.
KiCad File Templates.
Provides helper functions to create empty/minimal KiCad files with proper defaults. Useful for testing, programmatic generation, or starting new designs.
- class KiCadTemplates[source]
Bases:
objectHelper class for creating empty/minimal KiCad files.
All methods return objects with minimal required fields set to sensible defaults. You can then modify these objects before saving.
Example
>>> from kicadfiles.templates import KiCadTemplates >>> pcb = KiCadTemplates.pcb() >>> pcb.save_to_file("my_board.kicad_pcb")
- static footprint(library_link='Empty', version=20240108, generator='kicadfiles')[source]
Create an empty footprint file.
- Parameters:
library_link (str) – Footprint identifier (default: “Empty”).
version (int) – KiCad format version (default: 20240108).
generator (str) – Generator name (default: “kicadfiles”).
- Returns:
Minimal Footprint object.
- Return type:
Example
>>> fp = KiCadTemplates.footprint("MyComponent") >>> fp.pads = [] # Add pads >>> fp.save_to_file("component.kicad_mod")
- static pcb(version=20241229, generator='pcbnew', generator_version='9.0')[source]
Create an empty PCB file.
- Parameters:
version (int) – KiCad format version (default: 20241229 for KiCad 9.0).
generator (str) – Generator name (default: “pcbnew”).
generator_version (str) – Generator version (default: “9.0”).
- Returns:
Minimal KicadPcb object.
- Return type:
Example
>>> pcb = KiCadTemplates.pcb() >>> pcb.footprints = [] # Add footprints >>> pcb.save_to_file("board.kicad_pcb")
- static symbol_library(version=20241209, generator='kicadfiles')[source]
Create an empty symbol library file.
- Parameters:
version (int) – KiCad format version (default: 20241209 for KiCad 9.0).
generator (str) – Generator name (default: “kicadfiles”).
- Returns:
Minimal KicadSymbolLib object.
- Return type:
Example
>>> lib = KiCadTemplates.symbol_library() >>> lib.symbols = [] # Add symbols >>> lib.save_to_file("library.kicad_sym")
- static worksheet(version=20231003, generator='kicadfiles')[source]
Create an empty worksheet/drawing sheet file.
- Parameters:
version (int) – KiCad format version (default: 20231003).
generator (str) – Generator name (default: “kicadfiles”).
- Returns:
Minimal KicadWks object.
- Return type:
Example
>>> wks = KiCadTemplates.worksheet() >>> wks.save_to_file("template.kicad_wks")