Skip to content

Commit

Permalink
Replace type comments with type annotations (#130)
Browse files Browse the repository at this point in the history
Also correct type annotations where needed and remove them were the type
can be inferred.
  • Loading branch information
rnestler authored May 20, 2024
1 parent 7bfc1ae commit d6eede5
Show file tree
Hide file tree
Showing 11 changed files with 51 additions and 51 deletions.
4 changes: 2 additions & 2 deletions common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import re
from datetime import datetime

from typing import Any, Dict, Iterable, List, Union
from typing import Any, Dict, Iterable, List, OrderedDict, Union

# String escape sequences
STRING_ESCAPE_SEQUENCES = (
Expand All @@ -24,7 +24,7 @@

def init_cache(uuid_cache_file: str) -> Dict[str, str]:
print('Loading cache: {}'.format(uuid_cache_file))
uuid_cache = collections.OrderedDict() # type: Dict[str, str]
uuid_cache: OrderedDict[str, str] = collections.OrderedDict()
try:
with open(uuid_cache_file, 'r') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
Expand Down
10 changes: 5 additions & 5 deletions entities/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def __init__(self, uuid: str, symbol_uuid: SymbolUUID, position: Position,
self.rotation = rotation
self.required = required
self.suffix = suffix
self.pins = [] # type: List[PinSignalMap]
self.pins: List[PinSignalMap] = []

def add_pin_signal_map(self, pin_signal_map: PinSignalMap) -> None:
self.pins.append(pin_signal_map)
Expand Down Expand Up @@ -144,7 +144,7 @@ def __init__(self, uuid: str, norm: Norm, name: Name, description: Description,
self.norm = norm
self.name = name
self.description = description
self.gates = [gate] # type: List[Gate]
self.gates = [gate]

def add_gate(self, gate_map: Gate) -> None:
self.gates.append(gate_map)
Expand Down Expand Up @@ -178,9 +178,9 @@ def __init__(self, uuid: str, name: Name, description: Description,
self.schematic_only = schematic_only
self.default_value = default_value
self.prefix = prefix
self.signals = [] # type: List[Signal]
self.variants = [] # type: List[Variant]
self.approvals = [] # type: List[str]
self.signals: List[Signal] = []
self.variants: List[Variant] = []
self.approvals: List[str] = []

def add_approval(self, approval: str) -> None:
self.approvals.append(approval)
Expand Down
6 changes: 3 additions & 3 deletions entities/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ def __init__(self, uuid: str, name: Name, description: Description,
self.categories = categories
self.component_uuid = component_uuid
self.package_uuid = package_uuid
self.pads = [] # type: List[ComponentPad]
self.parts = [] # type: List[Part]
self.approvals = [] # type: List[str]
self.pads: List[ComponentPad] = []
self.parts: List[Part] = []
self.approvals: List[str] = []

def add_pad(self, pad: ComponentPad) -> None:
self.pads.append(pad)
Expand Down
18 changes: 9 additions & 9 deletions entities/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,11 +256,11 @@ def __init__(self, uuid: str, name: Name, description: Description,
self.description = description
self.position_3d = position_3d
self.rotation_3d = rotation_3d
self.pads = [] # type: List[FootprintPad]
self.models_3d = [] # type: List[Footprint3DModel]
self.polygons = [] # type: List[Polygon]
self.circles = [] # type: List[Circle]
self.texts = [] # type: List[StrokeText]
self.pads: List[FootprintPad] = []
self.models_3d: List[Footprint3DModel] = []
self.polygons: List[Polygon] = []
self.circles: List[Circle] = []
self.texts: List[StrokeText] = []

def add_pad(self, pad: FootprintPad) -> None:
self.pads.append(pad)
Expand Down Expand Up @@ -308,10 +308,10 @@ def __init__(self, uuid: str, name: Name, description: Description,
self.generated_by = generated_by
self.categories = categories
self.assembly_type = assembly_type
self.pads = [] # type: List[PackagePad]
self.models_3d = [] # type: List[Package3DModel]
self.footprints = [] # type: List[Footprint]
self.approvals = [] # type: List[str]
self.pads: List[PackagePad] = []
self.models_3d: List[Package3DModel] = []
self.footprints: List[Footprint] = []
self.approvals: List[str] = []

def add_pad(self, pad: PackagePad) -> None:
self.pads.append(pad)
Expand Down
10 changes: 5 additions & 5 deletions entities/symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ def __init__(self, uuid: str, name: Name, description: Description,
self.deprecated = deprecated
self.generated_by = generated_by
self.categories = categories
self.pins = [] # type: List[Pin]
self.polygons = [] # type: List[Polygon]
self.circles = [] # type: List[Circle]
self.texts = [] # type: List[Text]
self.approvals = [] # type: List[str]
self.pins: List[Pin] = []
self.polygons: List[Polygon] = []
self.circles: List[Circle] = []
self.texts: List[Text] = []
self.approvals: List[str] = []

def add_pin(self, pin: Pin) -> None:
self.pins.append(pin)
Expand Down
10 changes: 5 additions & 5 deletions generate_chip.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from os import path
from uuid import uuid4

from typing import Any, Dict, Iterable, Optional, Tuple
from typing import Dict, Iterable, Optional, Tuple

from common import format_ipc_dimension as fd
from common import init_cache, now, save_cache
Expand Down Expand Up @@ -198,10 +198,10 @@ def generate_pkg(
) -> None:
category = 'pkg'
for config in configs:
fmt_params = {
fmt_params: Dict[str, str] = {
'size_metric': config.size_metric(),
'size_imperial': config.size_imperial(),
} # type: Dict[str, Any]
}
fmt_params_name = {
**fmt_params,
'length': fd(config.body.length),
Expand Down Expand Up @@ -699,10 +699,10 @@ def generate_dev(
) -> None:
category = 'dev'
for (size_metric, size_imperial, pkg_name) in packages:
fmt_params = {
fmt_params: Dict[str, str] = {
'size_metric': size_metric,
'size_imperial': size_imperial,
} # type: Dict[str, Any]
}
full_name = name.format(**fmt_params)
full_desc = description.format(**fmt_params) + \
"\n\nGenerated with {}".format(generator)
Expand Down
2 changes: 1 addition & 1 deletion generate_dfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ def _generate_footprint(key: str, name: str, pad_extension: float) -> None:


if __name__ == '__main__':
generated_packages = [] # type: List[str]
generated_packages: List[str] = []

for config in JEDEC_CONFIGS:
# Find out which configs to create
Expand Down
2 changes: 1 addition & 1 deletion generate_led.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ def _uuid(identifier: str) -> str:
warning = 'Note: Not generating 3D models unless the "--3d" argument is passed in!'
print(f'\033[1;33m{warning}\033[0m')

configs = [] # type: List[LedConfig]
configs: List[LedConfig] = []

# Generic LEDs
#
Expand Down
4 changes: 2 additions & 2 deletions generate_mosfet_dual.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ def generate_dev(
for fet_config in configs:
lines = []

fmt_params = {
fmt_params: Dict[str, Any] = {
'name': fet_config.name,
'max_voltage': fet_config.max_voltage,
} # type: Dict[str, Any]
}
full_name = name.format(**fmt_params)
full_desc = description.format(**fmt_params)

Expand Down
2 changes: 1 addition & 1 deletion generate_so.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ def generate_3d(
print(f'\033[1;33m{warning}\033[0m')

# SOIC
configs = [] # type: List[SoConfig]
configs: List[SoConfig] = []
for pin_count in [6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 30, 32]:
for height in [1.2, 1.4, 1.7, 2.7]:
pitch = 1.27
Expand Down
34 changes: 17 additions & 17 deletions generate_stm_mcu.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from os import listdir, path
from uuid import uuid4

from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple
from typing import Any, DefaultDict, Dict, Iterable, Iterator, List, Optional, Set, Tuple

import common
from common import human_sort_key, init_cache, save_cache
Expand Down Expand Up @@ -101,8 +101,8 @@ def __init__(

class SymbolPinPlacement:
def __init__(self) -> None:
self.left = [] # type: List[Tuple[str, int]]
self.right = [] # type: List[Tuple[str, int]]
self.left: List[Tuple[str, int]] = []
self.right: List[Tuple[str, int]] = []

def add_left_pin(self, pin_name: str, y_pos: int) -> None:
self.left.append((pin_name, y_pos))
Expand Down Expand Up @@ -176,24 +176,24 @@ def __init__(self, ref: str, info: Dict[str, Any], pins: Iterable[Pin]):
self.pins = list(pins)
self.flash = '{} KiB'.format(info['info']['flash'])
self.ram = '{} KiB'.format(info['info']['ram'])
self.io_count = info['info']['io'] # type: int
self.io_count: int = info['info']['io']
self.gpio_version = info['gpio_version'] if len(info['gpio_version']) else None
if 'frequency' in info['info']:
self.frequency = '{} MHz'.format(info['info']['frequency']) # type: Optional[str]
self.frequency: Optional[str] = '{} MHz'.format(info['info']['frequency'])
else:
self.frequency = None
if 'voltage' in info['info']:
self.voltage = '{:.2}-{:.2}V'.format(
self.voltage: Optional[str] = '{:.2}-{:.2}V'.format(
info['info']['voltage']['min'],
info['info']['voltage']['max'],
) # type: Optional[str]
)
else:
self.voltage = None
if 'temperature' in info['info']:
self.temperature = '{:.0f}-{:.0f}°C'.format(
self.temperature: Optional[str] = '{:.0f}-{:.0f}°C'.format(
info['info']['temperature']['min'],
info['info']['temperature']['max'],
) # type: Optional[str]
)
else:
self.temperature = None

Expand Down Expand Up @@ -228,7 +228,7 @@ def _cleanup_pin_name(pin_name: str) -> str:
@classmethod
def from_json(cls, ref: str, info: Dict[str, Any]) -> 'MCU':
# Collect pins, grouped by number
pin_map = defaultdict(list) # type: Dict[str, List[Pin]]
pin_map: DefaultDict[str, List[Pin]] = defaultdict(list)
for entry in info['pinout']:
if entry['type'] == 'NC' and len(entry['signals']) == 0:
# Skip non-connected pins without signals
Expand All @@ -241,7 +241,7 @@ def from_json(cls, ref: str, info: Dict[str, Any]) -> 'MCU':
pin_map[entry['position']].append(pin)

# Merge pins into a flat list
pins = [] # type: List[Pin]
pins: List[Pin] = []
for group in pin_map.values():
# Merge signal names
merged_name = '/'.join(sorted((pin.name for pin in group), key=human_sort_key))
Expand Down Expand Up @@ -280,7 +280,7 @@ def get_pin_names_by_type(self, pin_type: str) -> List[PinName]:
Return all pin names of that type (without duplicates), sorted.
"""
pins = self.get_pins_by_type(pin_type)
known_names = set() # type: Set[str]
known_names: Set[str] = set()
result = []
i = 1
for pin in pins:
Expand Down Expand Up @@ -814,21 +814,21 @@ def generate_dev(mcu: MCU, symbol_map: Dict[str, str], base_lib_path: str, debug

def generate(data: Dict[str, MCU], base_lib_path: str, debug: bool = False) -> None:
# A map mapping symbol names to UUIDs
symbol_map = {} # type: Dict[str, str]
symbol_map: Dict[str, str] = {}

print('\nProcessing {} MCUs'.format(len(data)))

# Group symbols
symbols = defaultdict(list) # type: Dict[str, List[MCU]]
symbols: DefaultDict[str, List[MCU]] = defaultdict(list)
for mcu in data.values():
symbols[mcu.symbol_identifier].append(mcu)
print('Generating {} symbols'.format(len(symbols)))

# Group components
components_tmp = defaultdict(list) # type: Dict[str, List[MCU]]
components_tmp: DefaultDict[str, List[MCU]] = defaultdict(list)
for mcu in data.values():
components_tmp[mcu.component_identifier].append(mcu)
components = defaultdict(list) # type: Dict[str, List[MCU]]
components: DefaultDict[str, List[MCU]] = defaultdict(list)
for k, v in components_tmp.items():
combined_name = v[0].ref_for_flash_variants([mcu.ref for mcu in v])
components[combined_name] = v
Expand Down Expand Up @@ -865,7 +865,7 @@ def generate(data: Dict[str, MCU], base_lib_path: str, debug: bool = False) -> N
args = parser.parse_args()

# Load and parse all data
data = {} # type: Dict[str, MCU]
data: Dict[str, MCU] = {}
for filename in listdir(args.data_dir):
# Note: Only process STM32 files for now, because the STM8 ref naming scheme is inconsistent.
# See https://github.com/LibrePCB-Libraries/STMicroelectronics.lplib/pull/5 for details.
Expand Down

0 comments on commit d6eede5

Please sign in to comment.