Skip to content

Commit d9c15ba

Browse files
committed
Fix Python warnings and errors, cleanup code
1 parent 9b14360 commit d9c15ba

11 files changed

Lines changed: 131 additions & 120 deletions

File tree

src/kiutils/board.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515

1616
from __future__ import annotations
1717

18-
from dataclasses import dataclass, field
19-
from typing import Optional, List, Dict
18+
from typing import Dict
2019
from os import path
2120

2221
from kiutils.items.common import Group, Image, Net, PageSettings, TitleBlock
@@ -27,7 +26,7 @@
2726
from kiutils.utils.strings import dequote
2827
from kiutils.utils import sexpr
2928
from kiutils.footprint import Footprint
30-
from kiutils.misc.config import KIUTILS_CREATE_NEW_VERSION_STR, KIUTILS_CREATE_NEW_GENERATOR_STR
29+
from kiutils.misc.config import *
3130

3231
@dataclass
3332
class Board():
@@ -189,10 +188,10 @@ def create_new(cls) -> Board:
189188
Returns:
190189
- Board: Empty board
191190
"""
192-
board = cls(
193-
version = KIUTILS_CREATE_NEW_VERSION_STR,
194-
generator = KIUTILS_CREATE_NEW_GENERATOR_STR
195-
)
191+
board = Board()
192+
board.version = KIUTILS_CREATE_NEW_VERSION_STR
193+
board.generator = KIUTILS_CREATE_NEW_GENERATOR_STR
194+
board.generator_version = KIUTILS_CREATE_NEW_GENERATOR_VERSION_STR
196195

197196
# Add all standard layers to board
198197
board.layers.extend([
@@ -267,8 +266,7 @@ def to_sexpr(self, indent=0, newline=True) -> str:
267266

268267
addNewLine = False
269268

270-
generator_version = f' (generator_version "{self.generator_version}")' if self.generator_version is not None else ''
271-
expression = f'{indents}(kicad_pcb (version {self.version}) (generator {self.generator}){generator_version}\n\n'
269+
expression = f'{indents}(kicad_pcb (version {self.version}) (generator {self.generator}) (generator_version "{self.generator_version}")\n\n'
272270
expression += self.general.to_sexpr(indent+2) + '\n'
273271
expression += self.paper.to_sexpr(indent+2)
274272
if self.titleBlock is not None:

src/kiutils/footprint.py

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,16 @@
1818
import calendar
1919
import datetime
2020
import re
21-
from dataclasses import dataclass, field
22-
from typing import Optional, List, Dict
21+
from typing import Dict
2322
from os import path
2423

2524
from kiutils.items.zones import Zone
26-
from kiutils.items.common import Image, Position, Coordinate, Net, Group, Font
25+
from kiutils.items.common import Image, Coordinate, Net, Group, Font
2726
from kiutils.items.fpitems import *
2827
from kiutils.items.gritems import *
2928
from kiutils.utils import sexpr
3029
from kiutils.utils.strings import dequote, remove_prefix
31-
from kiutils.misc.config import KIUTILS_CREATE_NEW_VERSION_STR
30+
from kiutils.misc.config import *
3231

3332
@dataclass
3433
class Attributes():
@@ -112,7 +111,7 @@ def to_sexpr(self, indent=0, newline=False) -> str:
112111
Returns:
113112
- str: S-Expression of this object
114113
"""
115-
if (self.type == None
114+
if (self.type is None
116115
and self.boardOnly == False
117116
and self.excludeFromBom == False
118117
and self.excludeFromPosFiles == False
@@ -980,32 +979,29 @@ def create_new(cls, library_id: str, value: str,
980979
if type not in ['smd', 'through_hole', 'other']:
981980
raise Exception("Unsupported type was given")
982981

983-
fp = cls(
984-
version = KIUTILS_CREATE_NEW_VERSION_STR,
985-
generator = 'kiutils'
986-
)
982+
fp = Footprint()
983+
fp.version = KIUTILS_CREATE_NEW_VERSION_STR
984+
fp.generator = KIUTILS_CREATE_NEW_GENERATOR_STR
985+
fp.generator_version = KIUTILS_CREATE_NEW_GENERATOR_VERSION_STR
987986
fp.libId = library_id
988987

989988
# Create text items that are created when adding a new footprint to a library
990-
# TODO - In v9 these are not FpTexts anymore but rather Properties
991-
fp.graphicItems.extend(
992-
[
993-
FpText(
994-
type = 'reference', text = reference, layer = 'F.SilkS',
995-
effects = Effects(font=Font(thickness=0.15)),
996-
position = Position(X=0, Y=-0.5, unlocked=True)
997-
),
998-
FpText(
999-
type = 'value', text = value, layer ='F.Fab',
1000-
effects = Effects(font=Font(thickness=0.15)),
1001-
position = Position(X=0, Y=1, unlocked=True)
1002-
),
1003-
FpText(
1004-
type = 'user', text = '${REFERENCE}', layer = 'F.Fab',
1005-
effects = Effects(font=Font(thickness=0.15)),
1006-
position = Position(X=0, Y=2.5, unlocked=True)
1007-
)
1008-
]
989+
fp.properties['Reference'] = FpProperty(
990+
type='Reference', text=reference, layer='F.SilkS',
991+
effects=Effects(font=Font(thickness=0.15)),
992+
at=Position(X=0, Y=-0.5, unlocked=True)
993+
),
994+
fp.properties['Value'] = FpProperty(
995+
type='Value', text=value, layer='F.Fab',
996+
effects=Effects(font=Font(thickness=0.15)),
997+
at=Position(X=0, Y=1, unlocked=True)
998+
),
999+
fp.graphicItems.append(
1000+
FpText(
1001+
type = 'user', text = '${REFERENCE}', layer = 'F.Fab',
1002+
effects = Effects(font=Font(thickness=0.15)),
1003+
position = Position(X=0, Y=2.5, unlocked=True)
1004+
)
10091005
)
10101006

10111007
# The type ``other`` does not set the attributes type token
@@ -1053,7 +1049,7 @@ def to_sexpr(self, indent=0, newline=True, layerInFirstLine=False) -> str:
10531049
placed = f' (placed yes)' if self.placed else ''
10541050
version = f' (version {self.version})' if self.version is not None else ''
10551051
generator = f' (generator {self.generator})' if self.generator is not None else ''
1056-
generator_version = f' (generator_version "{self.generator_version}")' if self.generator_version is not None else ''
1052+
generator_version = f' (generator_version "{self.generator_version}")'
10571053
tstamp = f' (uuid "{self.tstamp}")' if self.tstamp is not None else ''
10581054

10591055
expression = f'{indents}(footprint "{dequote(self.libId)}"{locked}{placed}{version}{generator}{generator_version}{tstamp}'

src/kiutils/items/common.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@ def from_sexpr(cls, exp: list) -> Font:
328328
for item in exp[1:]:
329329
if not isinstance(item, list):
330330
raise Exception(f"Property '{item}' which is not in key -> value mapping. Expression: {exp}")
331+
331332
if item[0] == 'face': object.face = item[1]
332333
if item[0] == 'size':
333334
object.height = item[1]
@@ -353,12 +354,12 @@ def to_sexpr(self, indent=0, newline=False) -> str:
353354
endline = '\n' if newline else ''
354355
face_name, thickness, bold, italic, linespacing, color = '', '', '', '', '', ''
355356

356-
if self.face is not None: face_name = f'(face "{dequote(self.face)}") '
357-
if self.thickness is not None: thickness = f' (thickness {self.thickness})'
358-
if self.bold == True: bold = ' (bold yes)'
359-
if self.italic == True: italic = ' (italic yes)'
360-
if self.lineSpacing is not None: linespacing = f' (line_spacing {self.lineSpacing})'
361-
if self.color is not None: color = f' {self.color.to_sexpr()}'
357+
if self.face is not None: face_name = f'(face "{dequote(self.face)}") '
358+
if self.thickness is not None: thickness = f' (thickness {self.thickness})'
359+
if self.bold: bold = ' (bold yes)'
360+
if self.italic: italic = ' (italic yes)'
361+
if self.lineSpacing is not None: linespacing = f' (line_spacing {self.lineSpacing})'
362+
if self.color is not None: color = f' {self.color.to_sexpr()}'
362363

363364
expression = f'{indents}(font {face_name}(size {self.height} {self.width}){color}{thickness}{bold}{italic}{linespacing}){endline}'
364365
return expression
@@ -424,7 +425,7 @@ def to_sexpr(self, indent=0, newline=False) -> str:
424425
endline = '\n' if newline else ''
425426

426427
if self.horizontally is None and self.vertically is None and self.mirror == False:
427-
return f'{indents}{endline}';
428+
return f'{indents}{endline}'
428429

429430
horizontally, vertically, mirror = '', '', ''
430431

@@ -970,7 +971,7 @@ class RenderCache():
970971
id: int = 0
971972
"""The ``id`` token is some number after the text. Defaults to 0."""
972973

973-
polygons: List[Position] = field(default_factory=list)
974+
polygons: List[RenderCachePolygon] = field(default_factory=list)
974975
"""The ``polygons`` token is a list of polygons that define the outline of the cached text"""
975976

976977
@classmethod
@@ -1015,7 +1016,7 @@ def to_sexpr(self, indent: int = 4, newline: bool = True) -> str:
10151016

10161017
expression = f'{indents}(render_cache "{dequote(self.text)}" {self.id}\n'
10171018
for poly in self.polygons:
1018-
expression += poly.to_sexpr(indent+2)
1019+
expression += poly.to_sexpr()
10191020
expression += f'{indents}){endline}'
10201021
return expression
10211022

@@ -1177,7 +1178,7 @@ class ProjectInstance(ABC):
11771178
"""The ``name`` token defines the name of the project instance"""
11781179

11791180
@abstractmethod
1180-
def from_sexpr(cls, exp: list) -> ProjectInstance:
1181+
def from_sexpr(self, cls, exp: list) -> ProjectInstance:
11811182
raise NotImplementedError
11821183

11831184
@abstractmethod

src/kiutils/items/gritems.py

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -187,50 +187,50 @@ def from_sexpr(cls, exp: list) -> GrTextBox:
187187
'Most definitely there were changes introduced between Kicad 7 and 9.'
188188
'If you know what you are doing, proceed to verify/fix and remove the exception.')
189189

190-
"""Convert the given S-Expression into a GrTextBox object
191-
192-
Args:
193-
- exp (list): Part of parsed S-Expression ``(gr_text_box ...)``
194-
195-
Raises:
196-
- Exception: When given parameter's type is not a list
197-
- Exception: When the first item of the list is not fp_text_box
198-
199-
Returns:
200-
- GrTextBox: Object of the class initialized with the given S-Expression
201-
"""
202-
if not isinstance(exp, list) or len(exp) < 2:
203-
raise Exception("Expression does not have the correct type")
204-
205-
if exp[0] != 'gr_text_box':
206-
raise Exception("Expression does not have the correct type")
207-
208-
object = cls()
209-
210-
# Extract "locked" token, if any is present
211-
if exp[1] == "locked" and not isinstance(exp[2], list):
212-
object.locked = True
213-
object.text = exp[2]
214-
start_at = 3
215-
else:
216-
object.text = exp[1]
217-
start_at = 2
218-
219-
for item in exp[start_at:]:
220-
if item[0] == 'start': object.start = Position.from_sexpr(item)
221-
if item[0] == 'end': object.end = Position.from_sexpr(item)
222-
if item[0] == 'pts':
223-
for point in item[1:]:
224-
object.pts.append(Position().from_sexpr(point))
225-
if item[0] == 'angle': object.angle = item[1]
226-
if item[0] == 'layer': object.layer = item[1]
227-
if item[0] == 'tstamp': object.tstamp = item[1]
228-
if item[0] == 'tstamp': object.uuid = item[1] # Haha :)
229-
if item[0] == 'effects': object.effects = Effects.from_sexpr(item)
230-
if item[0] == 'stroke': object.stroke = Stroke.from_sexpr(item)
231-
if item[0] == 'render_cache': object.renderCache = RenderCache.from_sexpr(item)
232-
233-
return object
190+
# """Convert the given S-Expression into a GrTextBox object
191+
#
192+
# Args:
193+
# - exp (list): Part of parsed S-Expression ``(gr_text_box ...)``
194+
#
195+
# Raises:
196+
# - Exception: When given parameter's type is not a list
197+
# - Exception: When the first item of the list is not fp_text_box
198+
#
199+
# Returns:
200+
# - GrTextBox: Object of the class initialized with the given S-Expression
201+
# """
202+
# if not isinstance(exp, list) or len(exp) < 2:
203+
# raise Exception("Expression does not have the correct type")
204+
#
205+
# if exp[0] != 'gr_text_box':
206+
# raise Exception("Expression does not have the correct type")
207+
#
208+
# object = cls()
209+
#
210+
# # Extract "locked" token, if any is present
211+
# if exp[1] == "locked" and not isinstance(exp[2], list):
212+
# object.locked = True
213+
# object.text = exp[2]
214+
# start_at = 3
215+
# else:
216+
# object.text = exp[1]
217+
# start_at = 2
218+
#
219+
# for item in exp[start_at:]:
220+
# if item[0] == 'start': object.start = Position.from_sexpr(item)
221+
# if item[0] == 'end': object.end = Position.from_sexpr(item)
222+
# if item[0] == 'pts':
223+
# for point in item[1:]:
224+
# object.pts.append(Position().from_sexpr(point))
225+
# if item[0] == 'angle': object.angle = item[1]
226+
# if item[0] == 'layer': object.layer = item[1]
227+
# if item[0] == 'tstamp': object.tstamp = item[1]
228+
# if item[0] == 'tstamp': object.uuid = item[1] # Haha :)
229+
# if item[0] == 'effects': object.effects = Effects.from_sexpr(item)
230+
# if item[0] == 'stroke': object.stroke = Stroke.from_sexpr(item)
231+
# if item[0] == 'render_cache': object.renderCache = RenderCache.from_sexpr(item)
232+
#
233+
# return object
234234

235235
def to_sexpr(self, indent: int = 2, newline: bool = True) -> str:
236236
"""Generate the S-Expression representing this object

src/kiutils/items/schitems.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1062,7 +1062,7 @@ def libId(self, symbol_id: str):
10621062
# Available since KiCad v9
10631063

10641064
# TODO Missing docs
1065-
excludeFromSim: Optinal[str] = None
1065+
excludeFromSim: Optional[str] = None
10661066

10671067
@classmethod
10681068
def from_sexpr(cls, exp: list) -> SchematicSymbol:

src/kiutils/items/syitems.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from dataclasses import dataclass, field
2121
from typing import List, Optional
2222

23-
from kiutils.items.common import Fill, Position, Stroke, Effects, Fill
23+
from kiutils.items.common import Position, Stroke, Effects, Fill
2424
from kiutils.utils.strings import dequote
2525

2626
@dataclass
@@ -79,9 +79,14 @@ def from_sexpr(cls, exp: list) -> SyArc:
7979
# Pretty sure this isn't the case but let's be safe
8080
if item == 'private':
8181
object.private = True
82+
continue
8283
else:
8384
raise Exception(f"Property '{item}' which is not in key -> value mapping. Expression: {exp}")
84-
if item[0] == 'private' and item[1] == 'yes': object.private = True
85+
86+
if item[0] == 'private' and item[1] == 'yes':
87+
object.private = True
88+
continue
89+
8590
if item[0] == 'start': object.start = Position().from_sexpr(item)
8691
if item[0] == 'mid': object.mid = Position().from_sexpr(item)
8792
if item[0] == 'end': object.end = Position().from_sexpr(item)
@@ -166,9 +171,14 @@ def from_sexpr(cls, exp: list) -> SyCircle:
166171
# Pretty sure this isn't the case but let's be safe
167172
if item == 'private':
168173
object.private = True
174+
continue
169175
else:
170176
raise Exception(f"Property '{item}' which is not in key -> value mapping. Expression: {exp}")
171-
if item[0] == 'private' and item[1] == 'yes': object.private = True
177+
178+
if item[0] == 'private' and item[1] == 'yes':
179+
object.private = True
180+
continue
181+
172182
if item[0] == 'center': object.center = Position().from_sexpr(item)
173183
if item[0] == 'radius': object.radius = item[1]
174184
if item[0] == 'stroke': object.stroke = Stroke().from_sexpr(item)
@@ -254,14 +264,15 @@ def to_sexpr(self, indent: int = 6, newline: bool = True) -> str:
254264
indents = ' '*indent
255265
endline = '\n' if newline else ''
256266

257-
expression = f'{indents}(curve\n'
258-
expression = f'{indents} (pts\n'
267+
expression = f'{indents}(curve\n'
268+
expression += f'{indents} (pts\n'
259269
for point in self.points:
260-
expression = f'{indents} (xy {point.X} {point.Y})\n'
261-
expression = f'{indents} )\n'
270+
expression += f'{indents} (xy {point.X} {point.Y})\n'
271+
expression += f'{indents} )\n'
262272
expression += self.stroke.to_sexpr(indent+2)
263273
expression += self.fill.to_sexpr(indent+2)
264274
expression += f'{indents}){endline}'
275+
265276
return expression
266277

267278
@dataclass
@@ -386,9 +397,14 @@ def from_sexpr(cls, exp: list) -> SyRect:
386397
# Pretty sure this isn't the case but let's be safe
387398
if item == 'private':
388399
object.private = True
400+
continue
389401
else:
390402
raise Exception(f"Property '{item}' which is not in key -> value mapping. Expression: {exp}")
391-
if item[0] == 'private' and item[1] == 'yes': object.private = True
403+
404+
if item[0] == 'private' and item[1] == 'yes':
405+
object.private = True
406+
continue
407+
392408
if item[0] == 'start': object.start = Position().from_sexpr(item)
393409
if item[0] == 'end': object.end = Position().from_sexpr(item)
394410
if item[0] == 'stroke': object.stroke = Stroke().from_sexpr(item)

src/kiutils/items/zones.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ def from_sexpr(cls, exp: list) -> FilledPolygon:
365365
raise Exception("We didn't deal with this so far."
366366
"A small modification such as checking that item[1] is yes or no might be needed."
367367
"Verify/fix if needed and remove this exception.")
368-
object.island = True
368+
# object.island = True
369369
if item[0] == 'pts':
370370
for position in item[1:]:
371371
object.coordinates.append(Position().from_sexpr(position))

0 commit comments

Comments
 (0)