kiutils package

Board files (kiutils.board)

Class to manage KiCad boards

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

20.02.2022 - created

Documentation taken from:

https://dev-docs.kicad.org/en/file-formats/sexpr-pcb/

class kiutils.board.Board(version: str = '', generator: str = '', general: ~kiutils.items.brditems.GeneralSettings = <factory>, paper: ~kiutils.items.common.PageSettings = <factory>, titleBlock: ~kiutils.items.common.TitleBlock | None = None, layers: ~typing.List[~kiutils.items.brditems.LayerToken] = <factory>, setup: ~kiutils.items.brditems.SetupData = <factory>, properties: ~typing.Dict[str, str] = <factory>, nets: ~typing.List[~kiutils.items.common.Net] = <factory>, footprints: ~typing.List[~kiutils.footprint.Footprint] = <factory>, graphicItems: ~typing.List = <factory>, traceItems: ~typing.List = <factory>, zones: ~typing.List[~kiutils.items.zones.Zone] = <factory>, dimensions: ~typing.List[~kiutils.items.dimensions.Dimension] = <factory>, targets: ~typing.List[~kiutils.items.brditems.Target] = <factory>, groups: ~typing.List[~kiutils.items.common.Group] = <factory>, filePath: str | None = None)

Bases: object

The board token defines a KiCad layout according to the board file format used in .kicad_pcb files.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-pcb/

version: str = ''

The version token defines the board version using the YYYYMMDD date format

generator: str = ''

The generator token defines the program used to write the file

general: GeneralSettings

The general token defines general information about the board

paper: PageSettings

The paper token defines informations about the page itself

titleBlock: TitleBlock | None = None

The titleBlock token defines author, date, revision, company and comments of the board

layers: List[LayerToken]

The layers token defines all of the layers used by the board

setup: SetupData

The setup token is used to store the current settings used by the board

properties: Dict[str, str]

The properties token holds a list of key-value properties of the board as a dictionary

nets: List[Net]

The nets token defines a list of nets used in the layout

footprints: List[Footprint]

The footprints token defines a list of footprints used in the layout

graphicItems: List

The graphicItems token defines a list of graphical items used in the layout. Possible tokens are found in kiutils.items.gritems

The Image token is supported since KiCad v7 and must be added into this list when used.

traceItems: List

The traceItems token defines a list of segments, arcs and vias used in the layout

zones: List[Zone]

The zones token defines a list of zones used in the layout

dimensions: List[Dimension]

The dimensions token defines a list of dimensions on the PCB

targets: List[Target]

The targets token defines a list of target markers on the PCB

groups: List[Group]

The groups token defines a list of groups used in the layout

filePath: str | None = None

The filePath token defines the path-like string to the board file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) Board

Convert the given S-Expresstion into a Board object

Args:
  • exp (list): Part of parsed S-Expression (kicad_pcb ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not kicad_pcb

Returns:
  • Board: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) Board

Load a board directly from a KiCad board file (.kicad_pcb) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • Footprint: Object of the Schematic class initialized with the given KiCad schematic

classmethod create_new() Board

Creates a new empty board with its attributes set as KiCad would create it

Returns:
  • Board: Empty board

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

Design Rules (kiutils.dru)

Classes for custom design rules (.kicad_dru) and its contents

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

26.06.2022 - created

Documentation taken from:

??? Syntax help in Pcbnew

class kiutils.dru.Constraint(type: str = 'clearance', min: str | None = None, opt: str | None = None, max: str | None = None, elements: ~typing.List[str] = <factory>)

Bases: object

The Constraint token defines a design rule’s constraint

type: str = 'clearance'

The type token defines the type of constraint. Defaults to clearance. Allowed types: - annular_width - Width of an annular ring - clearance - Clearance between two items - courtyard_clearance - Clearance between two courtyards - diff_pair_gap - Gap between differential pairs - diff_pair_uncoupled - ??? - disallow - ??? Do not allow this rule - edge_clearance - Clearance between the item and board edges - length - Length of the item - hole_clearance - Clearance between the item and holes - hole_size - Size of the holes associated with this item - silk_clearance - Clearance to silk screen - skew - Difference in length between the items associated with this constraint - track_width - Width of the tracks associated with this constraint - via_count - Number of vias - via_diameter - Diameter of vias associated with this constraint

min: str | None = None

The min token defines the minimum allowed in this constraint

opt: str | None = None

The opt token defines the optimum allowed in this constraint

max: str | None = None

The max token defines the maximum allowed in this constraint

elements: List[str]

The items token defines a list of zero or more element types to include in this constraint. The following element types are available: - buried_via - micro_via - via - graphic - hole - pad - text - track - zone

classmethod from_sexpr(exp: list) Constraint

Convert the given S-Expresstion into a Constraint object

Args:
  • exp (list): Part of parsed S-Expression (constraint ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the list’s first parameter is not the (constraint ..) token

Returns:
  • Constraint: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.dru.Rule(name: str = '', constraints: ~typing.List[~kiutils.dru.Constraint] = <factory>, condition: str = '', layer: str | None = None, severity: str | None = None)

Bases: object

The Rule token defines a custom design rule

name: str = ''

The name token defines the name of the custom design rule

constraints: List[Constraint]

The constraints token defines a list of constraints for this custom design rule

condition: str = ''

The condition token defines the conditions that apply for this rule. Check KiCad syntax reference for more information. Example rule: - A.inDiffPair(‘*’) && !AB.isCoupledDiffPair()

layer: str | None = None

The optional layer token defines the canonical layer the rule applys to

severity: str | None = None

The optional severity token defines the severity of the design rule. Valid values are warning, error, exclusion or ignore.

Available since KiCad v7

classmethod from_sexpr(exp: list) Rule

Convert the given S-Expresstion into a Rule object

Args:
  • exp (list): Part of parsed S-Expression (rule ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the list’s first parameter is not the (rule ..) token

Returns:
  • Rule: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 0)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

Returns:
  • str: S-Expression of this object

class kiutils.dru.DesignRules(version: int = 1, rules: ~typing.List[~kiutils.dru.Rule] = <factory>, filePath: str | None = None)

Bases: object

The DesignRules token defines a set of custom design rules (.kicad_dru files)

version: int = 1

The version token defines the version of the file for the KiCad parser. Defaults to 1.

rules: List[Rule]

The rules token defines a list of custom design rules

filePath: str | None = None

The filePath token defines the path-like string to the schematic file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) DesignRules

Convert the given S-Expresstion into a DesignRules object

Args:
  • exp (list): Part of parsed S-Expression (version ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the list’s first parameter is not the (version ..) token

Returns:
  • DesignRules: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) DesignRules

Load a custom design rules set directly from a KiCad design rules file (.kicad_dru) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • Footprint: Object of the DesignRules class initialized with the given KiCad file

classmethod create_new() DesignRules

Creates a new empty design rules set as KiCad would create it

Returns:
  • DesignRules: Empty design rules set

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=False)

Generate the S-Expression representing this object

Args:

indent (int, optional): Number of whitespaces used to indent the output. Defaults to 0. newline (bool, optional): Adds a newline to the end of the output. Defaults to False.

Returns:

str: S-Expression of this object

Footprints (kiutils.footprint)

Classes to manage KiCad footprints

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

02.02.2022 - created

Documentation taken from:

https://dev-docs.kicad.org/en/file-formats/sexpr-footprint/

class kiutils.footprint.Attributes(type: str | None = None, boardOnly: bool = False, excludeFromPosFiles: bool = False, excludeFromBom: bool = False, allowMissingCourtyard: bool = False)

Bases: object

The attr token defines the list of attributes of a footprint.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_footprint_attributes

type: str | None = None

The optional type token defines the type of footprint. Valid footprint types are smd and through_hole. May be none when no attributes are set.

boardOnly: bool = False

The optional boardOnly token indicates that the footprint is only defined in the board and has no reference to any schematic symbol

excludeFromPosFiles: bool = False

The optional excludeFromPosFiles token indicates that the footprint position information should not be included when creating position files

excludeFromBom: bool = False

The optional excludeFromBom token indicates that the footprint should be excluded when creating bill of materials (BOM) files

allowMissingCourtyard: bool = False

The optional allowMissingCourtyard token indicates if the footprint generates a “missing courtyard” DRC violation.

Available since KiCad 7

classmethod from_sexpr(exp: list) Attributes

Convert the given S-Expresstion into a Attributes object

Args:
  • exp (list): Part of parsed S-Expression (attr ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not attr

Returns:
  • Attributes: Object of the class initialized with the given S-Expression

to_sexpr(indent=0, newline=False) str

Generate the S-Expression representing this object. Will return an empty string, if the following attributes are selected: - type: None - boardOnly: False - excludeFromBom: False - excludeFromPosFiles: False - allowMissingCourtyard: False

KiCad won’t add the (attr ..) token to a footprint when this combination is selected.

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.footprint.Model(path: str = '', pos: ~kiutils.items.common.Coordinate = <factory>, scale: ~kiutils.items.common.Coordinate = <factory>, rotate: ~kiutils.items.common.Coordinate = <factory>, hide: bool = False, opacity: float | None = None)

Bases: object

The model token defines the 3D model associated with a footprint.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_footprint_3d_model

path: str = ''

The path attribute is the path and file name of the 3D model

pos: Coordinate

The pos token specifies the 3D position coordinates of the model relative to the footprint

scale: Coordinate

The scale token specifies the model scale factor for each 3D axis

rotate: Coordinate

The rotate token specifies the model rotation for each 3D axis relative to the footprint

hide: bool = False

The hide token specifies if the 3d model is visible or not

opacity: float | None = None

The optional opacity token specifies the opacity of the 3D model on a scale between 1.0 and 0.0.

classmethod from_sexpr(exp: list) Model

Convert the given S-Expresstion into a Model object

Args:
  • exp (list): Part of parsed S-Expression (model ...)

Raises:
  • Exception: When given parameter’s type is not a list or the list is not 5 long

  • Exception: When the first item of the list is not model

Returns:
  • Model: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.footprint.DrillDefinition(oval: bool = False, diameter: float = 0.0, width: float | None = None, offset: Position | None = None)

Bases: object

The drill token defines the drill attributes for a footprint pad.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_pad_drill_definition

oval: bool = False

The oval token defines if the drill is oval instead of round

diameter: float = 0.0

The diameter attribute defines the drill diameter

width: float | None = None

The optional width attribute defines the width of the slot for oval drills

offset: Position | None = None

The optional offset token defines the drill offset coordinates from the center of the pad

classmethod from_sexpr(exp: list) DrillDefinition

Convert the given S-Expresstion into a DrillDefinition object

Args:
  • exp (list): Part of parsed S-Expression (drill ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not drill

Returns:
  • DrillDefinition: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 0, newline: bool = False) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.footprint.PadOptions(clearance: str = 'outline', anchor: str = 'rect')

Bases: object

The options token attributes define the settings used for custom pads. This token is only used when a custom pad is defined.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_custom_pad_options

clearance: str = 'outline'

The clearance token defines the type of clearance used for a custom pad. Valid clearance types are outline and convexhull.

anchor: str = 'rect'

The anchor token defines the anchor pad shape of a custom pad. Valid anchor pad shapes are rect and circle.

classmethod from_sexpr(exp: list) PadOptions

Convert the given S-Expresstion into a PadOptions object

Args:
  • exp (list): Part of parsed S-Expression (options ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not options

Returns:
  • PadOptions: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 0, newline: bool = False) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.footprint.Pad(number: str = 'x', type: str = 'smd', shape: str = 'rect', position: ~kiutils.items.common.Position = <factory>, locked: bool = False, size: ~kiutils.items.common.Position = <factory>, drill: ~kiutils.footprint.DrillDefinition | None = None, layers: ~typing.List[str] = <factory>, property: str | None = None, removeUnusedLayers: bool = False, keepEndLayers: bool = False, roundrectRatio: float | None = None, chamferRatio: float | None = None, chamfer: ~typing.List[str] = <factory>, net: ~kiutils.items.common.Net | None = None, tstamp: str | None = None, pinFunction: str | None = None, pinType: str | None = None, dieLength: float | None = None, solderMaskMargin: float | None = None, solderPasteMargin: float | None = None, solderPasteMarginRatio: float | None = None, clearance: float | None = None, zoneConnect: int | None = None, thermalWidth: float | None = None, thermalGap: float | None = None, customPadOptions: ~kiutils.footprint.PadOptions | None = None, customPadPrimitives: ~typing.List = <factory>)

Bases: object

The pad token defines a pad in a footprint definition.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_footprint_pad

number: str = 'x'

The number attribute is the pad number

type: str = 'smd'

The pad type can be defined as thru_hole, smd, connect, or np_thru_hole

shape: str = 'rect'

The pad shape can be defined as circle, rect, oval, trapezoid, roundrect, or custom

position: Position

The position defines the X and Y coordinates and optional orientation angle of the pad

locked: bool = False

The optional locked token defines if the footprint pad can be edited

size: Position

The size token defines the width and height of the pad

drill: DrillDefinition | None = None

The optional pad drill token defines the pad drill requirements

layers: List[str]

The layers token defines the layer or layers the pad reside on

property: str | None = None

The optional property token defines any special properties for the pad. Valid properties are pad_prop_bga, pad_prop_fiducial_glob, pad_prop_fiducial_loc, pad_prop_testpoint, pad_prop_heatsink, pad_prop_heatsink, and pad_prop_castellated

removeUnusedLayers: bool = False

The optional removeUnusedLayers token specifies that the copper should be removed from any layers the pad is not connected to

keepEndLayers: bool = False

The optional keepEndLayers token specifies that the top and bottom layers should be retained when removing the copper from unused layers

roundrectRatio: float | None = None

The optional roundrectRatio token defines the scaling factor of the pad to corner radius for rounded rectangular and chamfered corner rectangular pads. The scaling factor is a number between 0 and 1.

chamferRatio: float | None = None

The optional chamferRatio token defines the scaling factor of the pad to chamfer size. The scaling factor is a number between 0 and 1.

chamfer: List[str]

The optional chamfer token defines a list of one or more rectangular pad corners that get chamfered. Valid chamfer corner attributes are top_left, top_right, bottom_left, and bottom_right.

net: Net | None = None

The optional net token defines the integer number and name string of the net connection for the pad.

tstamp: str | None = None

The optional tstamp token defines the unique identifier of the pad object

pinFunction: str | None = None

The optional pinFunction token attribute defines the associated schematic symbol pin name

pinType: str | None = None

The optional pinType token attribute defines the associated schematic pin electrical type

dieLength: float | None = None

The optional dieLength token attribute defines the die length between the component pad and physical chip inside the component package

solderMaskMargin: float | None = None

The optional solderMaskMargin token attribute defines the distance between the pad and the solder mask for the pad. If not set, the footprint solder_mask_margin is used.

solderPasteMargin: float | None = None

The optional solderPasteMargin token attribute defines the distance the solder paste should be changed for the pad

solderPasteMarginRatio: float | None = None

The optional solderPasteMarginRatio token attribute defines the percentage to reduce the pad outline by to generate the solder paste size

clearance: float | None = None

The optional clearance token attribute defines the clearance from all copper to the pad. If not set, the footprint clearance is used.

zoneConnect: int | None = None

The optional zoneConnect token attribute defines type of zone connect for the pad. If not defined, the footprint zone_connection setting is used. Valid connection types are integers values from 0 to 3 which defines: - 0: Pad is not connect to zone - 1: Pad is connected to zone using thermal relief - 2: Pad is connected to zone using solid fill - 3: Only through hold pad is connected to zone using thermal relief

thermalWidth: float | None = None

The optional thermalWidth token attribute defines the thermal relief spoke width used for zone connection for the pad. This only affects a pad connected to a zone with a thermal relief. If not set, the footprint thermal_width setting is used.

thermalGap: float | None = None

The optional thermalGap token attribute defines the distance from the pad to the zone of the thermal relief connection for the pad. This only affects a pad connected to a zone with a thermal relief. If not set, the footprint thermal_gap setting is used.

customPadOptions: PadOptions | None = None

The optional customPadOptions token defines the options when a custom pad is defined

customPadPrimitives: List

The optional customPadPrimitives defines the drawing objects and options used to define a custom pad

classmethod from_sexpr(exp: list) Pad

Convert the given S-Expresstion into a Pad object

Args:
  • exp (list): Part of parsed S-Expression (pad ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not pad

Returns:
  • Pad: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 2, newline: bool = True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.footprint.Footprint(libraryNickname: str | None = None, entryName: str | None = None, version: str | None = None, generator: str | None = None, locked: bool = False, placed: bool = False, layer: str = 'F.Cu', tedit: str = '64de79c2', tstamp: str | None = None, position: ~kiutils.items.common.Position | None = None, description: str | None = None, tags: str | None = None, properties: ~typing.Dict = <factory>, path: str | None = None, autoplaceCost90: int | None = None, autoplaceCost180: int | None = None, solderMaskMargin: float | None = None, solderPasteMargin: float | None = None, solderPasteRatio: float | None = None, clearance: float | None = None, zoneConnect: int | None = None, thermalWidth: float | None = None, thermalGap: float | None = None, attributes: ~kiutils.footprint.Attributes = <factory>, privateLayers: ~typing.List[str] = <factory>, graphicItems: ~typing.List = <factory>, pads: ~typing.List[~kiutils.footprint.Pad] = <factory>, zones: ~typing.List[~kiutils.items.zones.Zone] = <factory>, groups: ~typing.List[~kiutils.items.common.Group] = <factory>, models: ~typing.List[~kiutils.footprint.Model] = <factory>, filePath: str | None = None)

Bases: object

The footprint token defines a footprint.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_footprint

property libId: str

The lib_id token defines the link to footprint library of the footprint. This only applies to footprints defined in the board file format, in a regular footprint file this id defines the footprint’s name. In kiutils, the token is a combination of both the libraryNickname and entryName token. Setting the lib_id token will update those tokens accordingly.

Returns:
  • Symbol id in the following format: <libraryNickname>:<entryName> or <entryName>, if libraryNickname token is not set.

libraryNickname: str | None = None

The optional libraryNickname token defines which symbol library this symbol belongs to and is a part of the id token

entryName: str = None

The entryName token defines the actual name of the symbol and is a part of the id token

version: str | None = None

The version token attribute defines the symbol library version using the YYYYMMDD date format

generator: str | None = None

The generator token attribute defines the program used to write the file

locked: bool = False

The optional locked token defines a flag to indicate the footprint cannot be edited

placed: bool = False

The optional placed token defines a flag to indicate that the footprint has not been placed

layer: str = 'F.Cu'

The layer token defines the canonical layer the footprint is placed

tedit: str = '64de79c2'

The tedit token defines a the last time the footprint was edited

tstamp: str | None = None

The tstamp token defines the unique identifier for the footprint. This only applies to footprints defined in the board file format.

position: Position | None = None

The position token defines the X and Y coordinates and rotational angle of the footprint. This only applies to footprints defined in the board file format.

description: str | None = None

The optional description token defines a string containing the description of the footprint

tags: str | None = None

The optional tags token defines a string of search tags for the footprint

properties: Dict

The properties token defines dictionary of properties as key / value pairs where key being the name of the property and value being the description of the property

path: str | None = None

The path token defines the hierarchical path of the schematic symbol linked to the footprint. This only applies to footprints defined in the board file format.

autoplaceCost90: int | None = None

The optional autoplaceCost90 token defines the vertical cost of when using the automatic footprint placement tool. Valid values are integers 1 through 10. This only applies to footprints defined in the board file format.

autoplaceCost180: int | None = None

The optional autoplaceCost180 token defines the horizontal cost of when using the automatic footprint placement tool. Valid values are integers 1 through 10. This only applies to footprints defined in the board file format.

solderMaskMargin: float | None = None

The optional solderMaskMargin token defines the solder mask distance from all pads in the footprint. If not set, the board solder_mask_margin setting is used.

solderPasteMargin: float | None = None

The optional solderPasteMargin token defines the solder paste distance from all pads in the footprint. If not set, the board solder_paste_margin setting is used.

solderPasteRatio: float | None = None

The optional solderPasteRatio token defines the percentage of the pad size used to define the solder paste for all pads in the footprint. If not set, the board solder_paste_ratio setting is used.

clearance: float | None = None

The optional clearance token defines the clearance to all board copper objects for all pads in the footprint. If not set, the board clearance setting is used.

zoneConnect: int | None = None

The optional zoneConnect token defines how all pads are connected to filled zone. If not defined, then the zone connect_pads setting is used. Valid connection types are integers values from 0 to 3 which defines:

  • 0: Pads are not connect to zone

  • 1: Pads are connected to zone using thermal reliefs

  • 2: Pads are connected to zone using solid fill

  • 3: Only through hold pads are connected to zone using thermal reliefs

thermalWidth: float | None = None

The optional thermalWidth token defined the thermal relief spoke width used for zone connections for all pads in the footprint. This only affects pads connected to zones with thermal reliefs. If not set, the zone thermal_width setting is used.

thermalGap: float | None = None

The optional thermalGap is the distance from the pad to the zone of thermal relief connections for all pads in the footprint. If not set, the zone thermal_gap setting is used. If not set, the zone thermal_gap setting is used.

attributes: Attributes

The optional attributes section defines the attributes of the footprint

privateLayers: List[str]

The optional privateLayers token defines a list of private layers assigned to the footprint. Valid values are: User.[1-9], User.Drawings, User.Comments, User.Eco[1-2].

Available since KiCad v7.

graphicItems: List

The graphic objects section is a list of one or more graphical objects in the footprint. Possible items are defined in kiutils.items.fpitems. At minimum the reference designator and value text objects are defined. All other graphical objects are optional.

The Image token is supported since KiCad v7 and must be added into this list when used.

pads: List[Pad]

The optional pads section is a list of pads in the footprint

zones: List[Zone]

The optional zones section is a list of keep out zones in the footprint

groups: List[Group]

The optional groups section is a list of grouped objects in the footprint

models: List[Model]

The 3D model section defines the 3D model object associated with the footprint

filePath: str | None = None

The filePath token defines the path-like string to the library file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) Footprint

Convert the given S-Expresstion into a Footprint object

Args:
  • exp (list): Part of parsed S-Expression (footprint ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not footprint

Returns:
  • Footprint: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) Footprint

Load a footprint directly from a KiCad footprint file (.kicad_mod) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • Footprint: Object of the Footprint class initialized with the given KiCad footprint

classmethod create_new(library_id: str, value: str, type: str = 'other', reference: str = 'REF**') Footprint

Creates a new empty footprint with its attributes set as KiCad would create it

Args:
  • library_link (str): Denotes the name of the library as well as the footprint. Like Connector:Conn01x02)

  • value (str): The value text item (printed on the fabrication layer as value attribute)

  • type (str): Type of footprint (smd, through_hole or other). Defaults to ‘other’.

  • reference (str): Reference of the footprint. Defaults to REF**.

Raises:
  • Exception: When the given type is something other than listed above

Returns:
  • Footprint: Empty footprint

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=True, layerInFirstLine=False) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

  • layerInFirstLine (bool): Prints the layer token in the first line. Defaults to False

Returns:
  • str: S-Expression of this object

Library tables (kiutils.libraries)

Classes to manage KiCad footprint and symbol library tables

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

19.02.2022 - created

class kiutils.libraries.Library(name: str = '', type: str = 'KiCad', uri: str = '', options: str = '', description: str = '', active: bool = True)

Bases: object

The library token defines either a symbol library or a footprint library in a library table file (fp_lib_table or sym_lib_table)

name: str = ''

The name token defines the name of the library as displayed in the project

type: str = 'KiCad'

The type token defines the type of the library, usually KiCad

uri: str = ''

The uri token defines the path to the library files

options: str = ''

The options token (..) TBD

description: str = ''

The description token (..) TBD

active: bool = True

The active token sets if the library is loaded by KiCad

classmethod from_sexpr(exp: list) Library

Convert the given S-Expresstion into a Library object

Args:
  • exp (list): Part of parsed S-Expression (lib ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not lib

Returns:
  • Library: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.libraries.LibTable(type: str = 'sym_lib_table', libs: ~typing.List[~kiutils.libraries.Library] = <factory>, filePath: str | None = None)

Bases: object

The libtable token defines the fp_lib_table or sym_lib_table file of KiCad

type: str = 'sym_lib_table'

The type token defines the type of the library table. Valid values are fp_lib_table or sym_lib_table.

libs: List[Library]

The libs token holds a list of librarys that this library table object holds

filePath: str | None = None

The filePath token defines the path-like string to the library file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) LibTable

Convert the given S-Expresstion into a LibTable object

Args:
  • exp (list): Part of parsed S-Expression (sym_lib_table ...) or (fp_lib_table ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not lib

Returns:
  • LibTable: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) LibTable

Load a library table directly from a KiCad library table file and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • LibTable: Object of the LibTable class initialized with the given KiCad library table

classmethod create_new(type: str = 'sym_lib_table') LibTable

Creates a new empty library table with its attributes set as KiCad would create it

Args:
  • type (str): fp_lib_table or sym_lib_table. Defaults to the latter.

Returns:
  • Library: Empty library table of given type

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

Schematics (kiutils.schematic)

Class to manage KiCad schematics

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

19.02.2022 - created

Documentation taken from:

https://dev-docs.kicad.org/en/file-formats/sexpr-schematic/

class kiutils.schematic.Schematic(version: str = '20211014', generator: str = 'kiutils', uuid: str | None = None, paper: ~kiutils.items.common.PageSettings = <factory>, titleBlock: ~kiutils.items.common.TitleBlock | None = None, libSymbols: ~typing.List[~kiutils.symbol.Symbol] = <factory>, schematicSymbols: ~typing.List[~kiutils.items.schitems.SchematicSymbol] = <factory>, junctions: ~typing.List[~kiutils.items.schitems.Junction] = <factory>, noConnects: ~typing.List[~kiutils.items.schitems.NoConnect] = <factory>, busEntries: ~typing.List[~kiutils.items.schitems.BusEntry] = <factory>, busAliases: ~typing.List[~kiutils.items.schitems.BusAlias] = <factory>, graphicalItems: ~typing.List[~kiutils.items.schitems.Connection | ~kiutils.items.schitems.PolyLine] = <factory>, shapes: ~typing.List[~kiutils.items.schitems.Arc | ~kiutils.items.schitems.Circle | ~kiutils.items.schitems.Rectangle] = <factory>, images: ~typing.List[~kiutils.items.common.Image] = <factory>, texts: ~typing.List[~kiutils.items.schitems.Text] = <factory>, textBoxes: ~typing.List[~kiutils.items.schitems.TextBox] = <factory>, labels: ~typing.List[~kiutils.items.schitems.LocalLabel] = <factory>, globalLabels: ~typing.List[~kiutils.items.schitems.GlobalLabel] = <factory>, hierarchicalLabels: ~typing.List[~kiutils.items.schitems.HierarchicalLabel] = <factory>, netclassFlags: ~typing.List[~kiutils.items.schitems.NetclassFlag] = <factory>, sheets: ~typing.List[~kiutils.items.schitems.HierarchicalSheet] = <factory>, sheetInstances: ~typing.List[~kiutils.items.schitems.HierarchicalSheetInstance] = <factory>, symbolInstances: ~typing.List[~kiutils.items.schitems.SymbolInstance] = <factory>, filePath: str | None = None)

Bases: object

The schematic token represents a KiCad schematic as defined by the schematic file format

Documenatation:

https://dev-docs.kicad.org/en/file-formats/sexpr-schematic/

version: str = '20211014'

The version token attribute defines the schematic version using the YYYYMMDD date format

generator: str = 'kiutils'

The generator token attribute defines the program used to write the file

uuid: str | None = None

The optional uuid defines the universally unique identifier. Defaults to None.

paper: PageSettings

The paper token defines the drawing page size and orientation

titleBlock: TitleBlock | None = None

The titleBlock token defines author, date, revision, company and comments of the schematic

libSymbols: List[Symbol]

The libSymbols token defines a list of symbols that are used in the schematic

schematicSymbols: List[SchematicSymbol]

The schematicSymbols token defines a list of instances of symbols used in the schematic

junctions: List[Junction]

The junctions token defines a list of junctions used in the schematic

noConnects: List[NoConnect]

The noConnect token defines a list of no_connect markers used in the schematic

busEntries: List[BusEntry]

The busEntries token defines a list of bus_entry used in the schematic

busAliases: List[BusAlias]

The busAliases token defines a list of bus_alias used in the schematic

graphicalItems: List[Connection | PolyLine]

The graphicalItems token defines a list of bus, wire or polyline elements used in the schematic

shapes: List[Arc | Circle | Rectangle]

The shapes token defines a list of graphical shapes (Arc, Rectangle or Circle) used in the schematic.

Available since KiCad v7

images: List[Image]

The images token defines a list of images used in the schematic

texts: List[Text]

The text token defines a list of texts used in the schematic

textBoxes: List[TextBox]

The text_box token defines a list of text boxes used in the schematic

labels: List[LocalLabel]

The labels token defines a list of local labels used in the schematic

globalLabels: List[GlobalLabel]

The globalLabels token defines a list of global labels used in the schematic

hierarchicalLabels: List[HierarchicalLabel]

The herarchicalLabels token defines a list of hierarchical labels used in the schematic

netclassFlags: List[NetclassFlag]

The netclassFlags token defines a list of netclass flags used in the schematic.

Available since KiCad v7

sheets: List[HierarchicalSheet]

The sheets token defines a list of hierarchical sheets used in the schematic

sheetInstances: List[HierarchicalSheetInstance]

The sheetInstances token defines a list of instances of hierarchical sheets used in the schematic

symbolInstances: List[SymbolInstance]

The symbolInstances token defines a list of instances of symbols from libSymbols token used in the schematic

filePath: str | None = None

The filePath token defines the path-like string to the schematic file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) Schematic

Convert the given S-Expresstion into a Schematic object

Args:
  • exp (list): Part of parsed S-Expression (kicad_sch ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not kicad_sch

Returns:
  • Schematic: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) Schematic

Load a schematic directly from a KiCad schematic file (.kicad_sch) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • Schematic: Object of the Schematic class initialized with the given KiCad schematic

classmethod create_new() Schematic

Creates a new empty schematic page with its attributes set as KiCad would create it

Returns:
  • Schematic: Empty schematic

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

Symbols and Symbol Libraries (kiutils.symbol)

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

14.02.2022 - created

Documentation taken from:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_symbols

class kiutils.symbol.SymbolAlternativePin(pinName: 'str' = '', electricalType: 'str' = 'input', graphicalStyle: 'str' = 'line')

Bases: object

pinName: str = ''

The pinName token defines the name of the alternative pin function

electricalType: str = 'input'

The electricalType defines the pin electrical connection. See symbol documentation for valid pin electrical connection types and descriptions.

graphicalStyle: str = 'line'

The graphicalStyle defines the graphical style used to draw the pin. See symbol documentation for valid pin graphical styles and descriptions.

classmethod from_sexpr(exp: list) SymbolAlternativePin

Convert the given S-Expresstion into a SymbolAlternativePin object

Args:
  • exp (list): Part of parsed S-Expression (alternate ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not alternate

Returns:
  • SymbolAlternativePin: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 8, newline: bool = True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 8.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.symbol.SymbolPin(electricalType: str = 'input', graphicalStyle: str = 'line', position: ~kiutils.items.common.Position = <factory>, length: float = 0.254, name: str = '', nameEffects: ~kiutils.items.common.Effects | None = None, number: str = '0', numberEffects: ~kiutils.items.common.Effects | None = None, hide: bool = False, alternatePins: ~typing.List[~kiutils.symbol.SymbolAlternativePin] = <factory>)

Bases: object

The pin token defines a pin in a symbol definition.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_symbol_pin

electricalType: str = 'input'

The electricalType defines the pin electrical connection. See documentation below for valid pin electrical connection types and descriptions.

graphicalStyle: str = 'line'

The graphicalStyle defines the graphical style used to draw the pin. See documentation below for valid pin graphical styles and descriptions.

position: Position

The position defines the X and Y coordinates and rotation angle of the connection point of the pin relative to the symbol origin position

length: float = 0.254

The length token attribute defines the LENGTH of the pin

name: str = ''

The name token defines a string containing the name of the pin

nameEffects: Effects | None = None

The optional nameEffects token define how the pin’s name is displayed. This token is mandatory for KiCad v6 and was made optional since KiCad v7.

number: str = '0'

The number token defines a string containing the NUMBER of the pin

numberEffects: Effects | None = None

The optional numberEffects token define how the pin’s number is displayed. This token is mandatory for KiCad v6 and was made optional since KiCad v7.

hide: bool = False

The ‘hide’ token defines if the pin should be hidden

alternatePins: List[SymbolAlternativePin]

The ‘alternate’ token defines one or more alternative definitions for the symbol pin

classmethod from_sexpr(exp: list) SymbolPin

Convert the given S-Expresstion into a SymbolPin object

Args:
  • exp (list): Part of parsed S-Expression (pin ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not pin

Returns:
  • SymbolPin: Object of the class initialized with the given S-Expression

to_sexpr(indent: int = 4, newline: bool = True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 4.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.symbol.Symbol(libraryNickname: str | None = None, entryName: str | None = None, unitId: int | None = None, styleId: int | None = None, extends: str | None = None, hidePinNumbers: bool = False, pinNames: bool = False, pinNamesHide: bool = False, pinNamesOffset: float | None = None, inBom: bool | None = None, onBoard: bool | None = None, isPower: bool = False, properties: ~typing.List[~kiutils.items.common.Property] = <factory>, graphicItems: ~typing.List = <factory>, pins: ~typing.List[~kiutils.symbol.SymbolPin] = <factory>, units: ~typing.List[~kiutils.symbol.Symbol] = <factory>)

Bases: object

The symbol token defines a symbol or sub-unit of a parent symbol. There can be zero or more symbol tokens in a symbol library file.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-intro/index.html#_symbols

property libId: str

The lib_id token defines a unique “LIBRARY_ID” for each top level symbol in the library or a unique “UNIT_ID” for each unit embedded in a parent symbol. Library identifiers are only valid it top level symbols and unit identifiers are on valid as unit symbols inside a parent symbol.

The following conventions apply:
  • “LIBRARY_ID” (top-level symbol): [<libraryNickname>:]<entryName> (the library nickname part is optional here)

  • “UNIT_ID” (child symbol): <entryName>_<unitId>_<styleId>

In kiutils, the lib_id token is a combination of libraryNickname, entryName, unitId and styleId tokens. Setting the lib_id token will update all those tokens accordingly.

Returns:
  • If the libraryNickname is set: <libraryNickname>:<entryName>

  • If the libraryNickname is None: <entryName> or <entryName>_<unitId>_<styleId>, depending if these tokens are set.

libraryNickname: str | None = None

The optional libraryNickname token defines which symbol library this symbol belongs to and is a part of the id token

entryName: str = None

The entryName token defines the actual name of the symbol and is a part of the id token

unitId: int | None = None

The unitId token identifies which unit the symbol represents and is a part of the id token

styleId: int | None = None

The styleId token indicates which body style the unit represents and is a part of the id token

extends: str | None = None

The optional extends token attribute defines the “LIBRARY_ID” of another symbol inside the current library from which to derive a new symbol. Extended symbols currently can only have different symbol properties than their parent symbol.

hidePinNumbers: bool = False

The pin_numbers token defines the visibility setting of the symbol pin numbers for the entire symbol. If set to False, the all of the pin numbers in the symbol are visible.

pinNames: bool = False

The optional pinNames token defines the attributes for all of the pin names of the symbol. If the pinNames token is not defined, all symbol pins are shown with the default offset.

pinNamesHide: bool = False

The optional pinNamesOffset token defines the pin name of all pins should be hidden

pinNamesOffset: float | None = None

The optional pinNamesOffset token defines the pin name offset for all pin names of the symbol. If not defined, the pin name offset is 0.508mm (0.020”)

inBom: bool | None = None

The optional inBom token, defines if a symbol is to be include in the bill of material output. If undefined, the token will not be generated in self.to_sexpr().

onBoard: bool | None = None

The onBoard token, defines if a symbol is to be exported from the schematic to the printed circuit board. If undefined, the token will not be generated in self.to_sexpr().

isPower: bool = False

The isPower token’s documentation was not done yet ..

properties: List[Property]

The properties is a list of properties that define the symbol. The following properties are mandatory when defining a parent symbol: “Reference”, “Value”, “Footprint”, and “Datasheet”. All other properties are optional. Unit symbols cannot have any properties.

graphicItems: List

The graphicItems section is list of graphical arcs, circles, curves, lines, polygons, rectangles, text and text boxes that define the symbol drawing. Possible items are defined in kiutils.items.syitems. This section can be empty if the symbol has no graphical items.

pins: List[SymbolPin]

The pins section is a list of pins that are used by the symbol. This section can be empty if the symbol does not have any pins.

units: List[Symbol]

The units can be one or more child symbol tokens embedded in a parent symbol

classmethod from_sexpr(exp: list) Symbol

Convert the given S-Expression into a Symbol object

Args:
  • exp (list): Part of parsed S-Expression (symbol ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not symbol

Returns:
  • Symbol: Object of the class initialized with the given S-Expression

classmethod create_new(id: str, reference: str, value: str, footprint: str = '', datasheet: str = '') Symbol

Creates a new empty symbol as KiCad would create it

Args:
  • id (str): ID token of the symbol

  • reference (str): Reference designator

  • value (str): Value of the value property

  • footprint (str): Value of the footprint property. Defaults to “” (empty string).

  • datasheet (str): Value of the datasheet property. Defaults to “” (empty string).

Returns:
  • Symbol: New symbol initialized with default values

to_sexpr(indent: int = 2, newline: bool = True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.symbol.SymbolLib(version: str = '20211014', generator: str | None = None, symbols: ~typing.List[~kiutils.symbol.Symbol] = <factory>, filePath: str | None = None)

Bases: object

A symbol library defines the common format of .kicad_sym files. A symbol library may contain zero or more symbols.

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-symbol-lib/

version: str = '20211014'

The version token attribute defines the symbol library version using the YYYYMMDD date format

generator: str | None = None

The generator token attribute defines the program used to write the file

symbols: List[Symbol]

The symbols token defines a list of zero or more symbols that are part of the symbol library

filePath: str | None = None

The filePath token defines the path-like string to the library file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_file(filepath: str, encoding: str | None = None) SymbolLib

Load a symbol library directly from a KiCad footprint file (.kicad_sym) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • SymbolLib: Object of the SymbolLib class initialized with the given KiCad symbol library

classmethod from_sexpr(exp: list) SymbolLib

Convert the given S-Expresstion into a SymbolLib object

Args:
  • exp (list): Part of parsed S-Expression (kicad_symbol_lib ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not kicad_symbol_lib

Returns:
  • SymbolLib: Object of the class initialized with the given S-Expression

to_file(filepath=None, encoding: str | None = None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

  • encoding (str, optional): Encoding of the output file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent: int = 0, newline: bool = True) str

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

Worksheets (kiutils.wks)

Classes for worksheets (.kicad_wks) and its contents

Author:
  1. Marvin Mager - @mvnmgrx - 2022

License identifier:

GPL-3.0

Major changes:

24.06.2022 - created

Documentation taken from:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/

class kiutils.wks.WksFontSize(width: float = 1.0, height: float = 1.0)

Bases: object

The WksFontSize token defines the size of a font in a worksheet

width: float = 1.0

The width token defines the width of the font. Defaults to 1.

height: float = 1.0

The height token defines the height of the font. Defaults to 1.

classmethod from_sexpr(exp: list) WksFontSize

Convert the given S-Expresstion into a WksFontSize object

Args:
  • exp (list): Part of parsed S-Expression (size ...)

Raises:
  • Exception: When given parameter’s type is not a list or its length is not equal to 3

  • Exception: When the first item of the list is not size

Returns:
  • WksFontSize: Object of the class initialized with the given S-Expression

to_sexpr(indent=0, newline=False)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.wks.WksFont(linewidth: float | None = None, size: WksFontSize | None = None, bold: bool = False, italic: bool = False)

Bases: object

The WksFont token defines how a text is drawn

linewidth: float | None = None

The optional linewidth token defines the width of the font’s lines

size: WksFontSize | None = None

The optional size token defines the size of the font

bold: bool = False

The bold token defines if the font is drawn bold. Defaults to False.

italic: bool = False

The italic token defines if the font is drawn italic. Defaults to False.

classmethod from_sexpr(exp: list) WksFont

Convert the given S-Expresstion into a WksFont object

Args:
  • exp (list): Part of parsed S-Expression (font ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not font

Returns:
  • WksFont: Object of the class initialized with the given S-Expression

to_sexpr(indent=0, newline=False)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object. Will return an empty string, if all members of this

    class are set to None.

class kiutils.wks.WksPosition(X: float = 0.0, Y: float = 0.0, corner: str | None = None)

Bases: object

The WksPosition token defines the positional coordinates and rotation of an worksheet object.

X: float = 0.0

The X attribute defines the horizontal position of the object. Defaults to 0.

Y: float = 0.0

The Y attribute defines the vertical position of the object. Defaults to 0.

corner: str | None = None

The optional corner token is used to define the initial corner for repeating

classmethod from_sexpr(exp: list) WksPosition

Convert the given S-Expresstion into a WksPosition object

Args:
  • exp (list): Part of parsed S-Expression (xxx ...)

Raises:
  • Exception: When the given expression is not of type list or the list is less than

    3 items long

Returns:
  • WksPosition: Object of the class initialized with the given S-Expression

to_sexpr() str

This object does not have a direct S-Expression representation.

class kiutils.wks.Line(name: str = '', start: ~kiutils.wks.WksPosition = <factory>, end: ~kiutils.wks.WksPosition = <factory>, option: str | None = None, lineWidth: float | None = None, repeat: int | None = None, incrx: float | None = None, incry: float | None = None, comment: str | None = None)

Bases: object

The Line token defines how a line is drawn in a work sheet

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_graphical_line

name: str = ''

The name token defines the name of the line object

start: WksPosition

The start token defines the start position of the line

end: WksPosition

The end token defines the end position of the line

option: str | None = None

The optional option token defines on which pages the line shall be shown. Possible values are: - None: Item will be shown on all pages - notonpage1: On all pages except page 1 - page1only: Only visible on page 1

lineWidth: float | None = None

The optional lineWidth token attribute defines the width of the rectangle lines

repeat: int | None = None

The optional repeat token defines the count for repeated incremental lines

incrx: float | None = None

The optional incrx token defines the repeat distance on the X axis

incry: float | None = None

The optional incry token defines the repeat distance on the Y axis

comment: str | None = None

The optional comment token is a comment for the line object

classmethod from_sexpr(exp: list) Line

Convert the given S-Expresstion into a Line object

Args:
  • exp (list): Part of parsed S-Expression (line ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not tbtext

Returns:
  • Line: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.wks.Rect(name: str = '', start: ~kiutils.wks.WksPosition = <factory>, end: ~kiutils.wks.WksPosition = <factory>, option: str | None = None, lineWidth: float | None = None, repeat: int | None = None, incrx: float | None = None, incry: float | None = None, comment: str | None = None)

Bases: object

The Rect token defines how a rectangle is drawn in a work sheet

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_graphical_rectangle

name: str = ''

The name token defines the name of the rectangle object

start: WksPosition

The start token defines the start position of the rectangle

end: WksPosition

The end token defines the end position of the rectangle

option: str | None = None

The optional option token defines on which pages the rectangle shall be shown. Possible values are: - None: Item will be shown on all pages - notonpage1: On all pages except page 1 - page1only: Only visible on page 1

lineWidth: float | None = None

The optional lineWidth token attribute defines the width of the rectangle lines

repeat: int | None = None

The optional repeat token defines the count for repeated incremental rectangles

incrx: float | None = None

The optional incrx token defines the repeat distance on the X axis

incry: float | None = None

The optional incry token defines the repeat distance on the Y axis

comment: str | None = None

The optional comment token is a comment for the rectangle object

classmethod from_sexpr(exp: list) Rect

Convert the given S-Expresstion into a Rect object

Args:
  • exp (list): Part of parsed S-Expression (rect ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not rect

Returns:
  • Rect: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.wks.Polygon(name: str = '', position: ~kiutils.wks.WksPosition = <factory>, option: str | None = None, rotate: float | None = None, coordinates: ~typing.List[~kiutils.wks.WksPosition] = <factory>, repeat: int | None = None, incrx: float | None = None, incry: float | None = None, comment: str | None = None)

Bases: object

The Polygon token defines a graphical polygon in a worksheet

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_graphical_polygon

name: str = ''

The name token defines the name of the polygon

position: WksPosition

The position token defines the coordinates of the polygon

option: str | None = None

The optional option token defines on which pages the polygon shall be shown. Possible values are: - None: Item will be shown on all pages - notonpage1: On all pages except page 1 - page1only: Only visible on page 1

rotate: float | None = None

The optional rotate token defines the rotation angle of the polygon object

coordinates: List[WksPosition]

The coordinates token defines a list of X/Y coordinates that forms the polygon

repeat: int | None = None

The optional repeat token defines the count for repeated incremental polygons

incrx: float | None = None

The optional incrx token defines the repeat distance on the X axis

incry: float | None = None

The optional incry token defines the repeat distance on the Y axis

comment: str | None = None

The optional comment token is a comment for the polygon object

classmethod from_sexpr(exp: list) Polygon

Convert the given S-Expresstion into a Polygon object

Args:
  • exp (list): Part of parsed S-Expression (polygon ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not polygon

Returns:
  • Polygon: Object of the class initialized with the given S-Expression

to_sexpr(indent=0, newline=False)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.wks.Bitmap(name: str = '', position: ~kiutils.wks.WksPosition = <factory>, option: str | None = None, scale: float = 1.0, repeat: int | None = None, incrx: float | None = None, incry: float | None = None, comment: str | None = None, pngdata: ~typing.List[str] = <factory>)

Bases: object

The Polygon token defines on or more embedded images

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_image

name: str = ''

The name token defines the name of the bitmap

position: WksPosition

The position token defines the coordinates of the bitmap

option: str | None = None

The optional option token defines on which pages the image shall be shown. Possible values are: - None: Item will be shown on all pages - notonpage1: On all pages except page 1 - page1only: Only visible on page 1

scale: float = 1.0

The scale token defines the scale of the bitmap object

repeat: int | None = None

The optional repeat token defines the count for repeated incremental bitmaps

incrx: float | None = None

The optional incrx token defines the repeat distance on the X axis

incry: float | None = None

The optional incry token defines the repeat distance on the Y axis

comment: str | None = None

The optional comment token is a comment for the bitmap object

pngdata: List[str]

The pngdata token defines a list of strings representing up to 32 bytes per entry of the image being saved.

Format: - “xx xx xx xx xx (..) xx “

The list must be 32byte aligned, leaving a space after the last byte as shown in the format example.

classmethod from_sexpr(exp: list) Bitmap

Convert the given S-Expresstion into a Bitmap object

Args:
  • exp (list): Part of parsed S-Expression (bitmap ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not bitmap

Returns:
  • Bitmap: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.wks.TbText(text: str = '', name: str = '', position: ~kiutils.wks.WksPosition = <factory>, option: str | None = None, rotate: float | None = None, font: ~kiutils.wks.WksFont = <factory>, justify: ~kiutils.items.common.Justify | None = None, maxlen: float | None = None, maxheight: float | None = None, repeat: int | None = None, incrx: float | None = None, incry: float | None = None, incrlabel: int | None = None, comment: str | None = None)

Bases: object

The TbText token define text used in the title block of a work sheet

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_title_block_text

text: str = ''

The text token defines the text itself

name: str = ''

The name token defines the name of the text object

position: WksPosition

The position token defines the position of the text

option: str | None = None

The optional option token defines on which pages the text shall be shown. Possible values are: - None: Item will be shown on all pages - notonpage1: On all pages except page 1 - page1only: Only visible on page 1

rotate: float | None = None

The optional rotate token defines the rotation of the text in degrees

font: WksFont

The font token define how the text is drawn

justify: Justify | None = None

The optional justify token defines the justification of the text

maxlen: float | None = None

The optional maxlen token defines the maximum length of the text

maxheight: float | None = None

The optional maxheight token defines the maximum height of the text

repeat: int | None = None

The optional repeat token defines the count for repeated incremental text

incrx: float | None = None

The optional incrx token defines the repeat distance on the X axis

incry: float | None = None

The optional incry token defines the repeat distance on the Y axis

incrlabel: int | None = None

The optional incrlabel token defines the amount of characters that are moved with every repeated incremental text

comment: str | None = None

The optional comment token is a comment for the text object

classmethod from_sexpr(exp: list) TbText

Convert the given S-Expresstion into a TbText object

Args:
  • exp (list): Part of parsed S-Expression (tbtext ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not tbtext

Returns:
  • TbText: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.wks.TextSize(width: float = 1.5, height: float = 1.5)

Bases: object

The TextSize define the default width and height of text

width: float = 1.5

The width token defines the default width of a text element. Defaults to 1,5.

height: float = 1.5

The height token defines the default height of a text element. Defaults to 1,5.

classmethod from_sexpr(exp: list) TextSize

Convert the given S-Expresstion into a TextSize object

Args:
  • exp (list): Part of parsed S-Expression (textsize ...)

Raises:
  • Exception: When given parameter’s type is not a list or when its not exactly 3 long

  • Exception: When the first item of the list is not textsize

Returns:
  • TextSize: Object of the class initialized with the given S-Expression

to_sexpr(indent=0, newline=False)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to False.

Returns:
  • str: S-Expression of this object

class kiutils.wks.Setup(textSize: ~kiutils.wks.TextSize = <factory>, lineWidth: float = 0.15, textLineWidth: float = 0.15, leftMargin: float = 10.0, rightMargin: float = 10.0, topMargin: float = 10.0, bottomMargin: float = 10.0)

Bases: object

The setup token defines the configuration information for the work sheet

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_set_up_section

textSize: TextSize

The textSize token defines the default width and height of text

lineWidth: float = 0.15

The lineWidth token attribute defines the default width of lines. Defaults to 0,15.

textLineWidth: float = 0.15

The textLineWidth token attribute define the default width of the lines used to draw text. Defaults to 0,15.

leftMargin: float = 10.0

The leftMargin token defines the distance from the left edge of the page

rightMargin: float = 10.0

The rightMargin token defines the distance from the right edge of the page

topMargin: float = 10.0

The topMargin token defines the distance from the top edge of the page

bottomMargin: float = 10.0

The bottomMargin token defines the distance from the bottom edge of the page

classmethod from_sexpr(exp: list) Setup

Convert the given S-Expresstion into a Setup object

Args:
  • exp (list): Part of parsed S-Expression (setup ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not setup

Returns:
  • Setup: Object of the class initialized with the given S-Expression

to_sexpr(indent=2, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 2.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object

class kiutils.wks.WorkSheet(version: str = '20211014', generator: str = 'kiutils', setup: ~kiutils.wks.Setup = <factory>, drawingObjects: ~typing.List = <factory>, filePath: str | None = None)

Bases: object

The WorkSheet token defines a KiCad worksheet (.kicad_wks file)

Documentation:

https://dev-docs.kicad.org/en/file-formats/sexpr-worksheet/#_header_section

version: str = '20211014'

The version token defines the work sheet version using the YYYYMMDD date format

generator: str = 'kiutils'

The generator token defines the program used to write the file

setup: Setup

The setup token defines the configuration information for the work sheet

drawingObjects: List

The drawingObjects token can contain zero or more texts, lines, rectangles, polys or images

filePath: str | None = None

The filePath token defines the path-like string to the board file. Automatically set when self.from_file() is used. Allows the use of self.to_file() without parameters.

classmethod from_sexpr(exp: list) WorkSheet

Convert the given S-Expresstion into a WorkSheet object

Args:
  • exp (list): Part of parsed S-Expression (kicad_wks ...)

Raises:
  • Exception: When given parameter’s type is not a list

  • Exception: When the first item of the list is not kicad_wks

Returns:
  • WorkSheet: Object of the class initialized with the given S-Expression

classmethod from_file(filepath: str, encoding: str | None = None) WorkSheet

Load a worksheet directly from a KiCad worksheet file (.kicad_wks) and sets the self.filePath attribute to the given file path.

Args:
  • filepath (str): Path or path-like object that points to the file

  • encoding (str, optional): Encoding of the input file. Defaults to None (platform

    dependent encoding).

Raises:
  • Exception: If the given path is not a file

Returns:
  • WorkSheet: Object of the WorkSheet class initialized with the given KiCad worksheet

classmethod create_new() WorkSheet

Creates a new empty worksheet as KiCad would create it

Returns:

WorkSheet: A empty worksheet

to_file(filepath=None)

Save the object to a file in S-Expression format

Args:
  • filepath (str, optional): Path-like string to the file. Defaults to None. If not set,

    the attribute self.filePath will be used instead.

Raises:
  • Exception: If no file path is given via the argument or via self.filePath

to_sexpr(indent=0, newline=True)

Generate the S-Expression representing this object

Args:
  • indent (int): Number of whitespaces used to indent the output. Defaults to 0.

  • newline (bool): Adds a newline to the end of the output. Defaults to True.

Returns:
  • str: S-Expression of this object